Rendering
useRender picks what to render from the current state. It works like useEffect: pass the state's getter, add one case per group of states, and finish with use(), which returns what the matching case returned:
return finity
.useRender(state.value)
.case(["Loading"], () => <Spinner />)
.case(["Ready"], (ready) => <Resource resource={ready.resource} />)
.case(["Errored"], (errored) => (
<Retry onRetry={() => errored.transition({ kind: "Loading" })} />
))
.use();As with effects, use() only compiles once every state has a case.
useRender is in the React and Solid packages. @ghostry/finity-core has none, since rendering belongs to the framework.
Do you need it?
A switch on kind is checked for missing cases only when falling through it is an error. In React, declare the component's return type as React.JSX.Element, which excludes undefined. An inferred return type, or React.ReactNode, includes it, and a missing case compiles. With the declared type, a missing case falls through to the end of the function, and TypeScript reports that not every path returns a value:
function View(): React.JSX.Element {
const current = state.value();
switch (current.kind) {
case "Loading":
return <Spinner />;
case "Ready":
return <Resource resource={current.resource} />;
case "Errored":
return <Retry />;
}
}That works for most React components, and useRender is optional there.
In Solid, JSX.Element includes undefined, so a switch with a missing case still compiles, and renders nothing. Use useRender there, or end the switch with default: return never(current), using never from @ghostry/finity-core.
In Solid, a case runs once
A Solid component runs once, and so does a case: it's called when its states start matching, not again when the state changes within them. The state it receives updates in place while the case still matches. With .case(["Uploading"], …), a transition from Uploading to Uploading with new progress updates what's rendered, without calling the case again.
So read the state's properties where Solid tracks them, in JSX or another reactive scope:
.case(["Uploading"], (uploading) => <progress value={uploading.progress} />) // updates
.case(["Uploading"], ({ progress }) => <progress value={progress} />) // stays at its first valueDestructuring reads each property once, as it does with Solid's props.
Without JSX, return a function from the case, and Solid renders it reactively:
finity
.useRender(state.value)
.case(["Loading"], () => "Loading…")
.case(
["Uploading"],
(uploading) => () => `${Math.round(uploading.progress * 100)}%`,
)
.use();See Solid.
