Readme

Server-side Render React Mini Framework

This is very experimental, more of a prototype of an architecture, than a true framework

Example: https://www.val.town/v/stevekrouse/TodoApp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/** @jsxImportSource https://esm.sh/react */
import { renderToString } from "https://esm.sh/react-dom@18.2.0/server";
import { useEffect, useState } from "https://esm.sh/react@18.2.0";
import { extractValInfo } from "https://esm.town/v/pomdtr/extractValInfo?v=25";
import { html } from "https://esm.town/v/stevekrouse/html";
// button that's disabled until client react hydrates
export const Button = (props) => {
const [clientHydrated, setClientHydrated] = useState(false);
useEffect(() => setClientHydrated(true), []);
return <button disabled={!clientHydrated} {...props}></button>;
};
export const Form = ({ onSubmit, ...props }: any) => {
const [clientHydrated, setClientHydrated] = useState(false);
useEffect(() => setClientHydrated(true), []);
return (
<form
disabled={!clientHydrated}
onSubmit={async (e) => {
e.preventDefault();
const onData = onSubmit ? onSubmit(e) : () => 1;
const formData = new FormData(e.target as any);
const resp = await fetch("/", {
method: props.action ?? "POST",
body: formData,
});
await onData(resp);
}}
{...props}
>
</form>
);
};
export const hydrate = (importMetaURL: string) =>
async function(req: Request): Promise<Response> {
const { author, name } = extractValInfo(importMetaURL);
const valURL = `https://www.val.town/v/${author}/${name}`;
const moduleURL = `https://esm.town/v/${author}/${name}`;
const exports = await import(moduleURL);
const action = exports.action ?? (() => ({}));
const loader = exports.loader ?? (() => ({}));
const Component = exports.Component ?? (() => (
<div>
Error: Please ensure you <code>export Component</code>" in{" "}
<a target="_blank" href={valURL}>@{author}/{name}</a>.
</div>
));
if (req.method === "GET") {
const props = await loader(req);
const script = `
import { hydrateRoot } from "https://esm.sh/react-dom@18.2.0/client";
import { jsx as _jsx } from "https://esm.sh/react@18.2.0/jsx-runtime";
import { Component } from "https://esm.town/v/${author}/${name}";
let props = ${JSON.stringify(props)}
try {
hydrateRoot(document, _jsx(Component, props));
} catch (e) {
console.error(e)
}
`;
return html(renderToString(
<>
<Component {...props} />
<script type="module" dangerouslySetInnerHTML={{ __html: script }} />
</>,
));
} else {
return action(req);
}
};
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.