react-split-state
A function sets a state to true before an await and back after it (a loading flag), and sets other states after the await (the data, the error).
Why: that is one async state kept in three useStates, and they can disagree. An error from this request sits next to the data from the previous one. An older, slower request finishes last and turns off the newer one's loading while it is still running. AsyncState is one value that is Idle, Loading, Ready or Failed, so it can't be two at once. Guide: React.
✕ Rejectedreact-split-state
tsx
import { useState } from "react";
import { isErr } from "@evobug_com/safe-ts-std/result";
import { fetchOrders, type Order } from "./api";
export function Orders() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [orders, setOrders] = useState<readonly Order[]>([]);
const load = async (): Promise<void> => {
setLoading(true);
const result = await fetchOrders();
if (isErr(result)) setError(result.error.message);
else setOrders(result);
setLoading(false);
};
return (
<>
<button onClick={() => void load()}>Load</button>
{loading && <p>Loading…</p>}
{error !== "" && <p>{error}</p>}
{orders.map((order) => <p key={order.id}>{order.total}</p>)}
</>
);
}✓ Accepted0 diagnostics
tsx
import { Match } from "@evobug_com/safe-ts-react/match";
import { useTask } from "@evobug_com/safe-ts-react/task";
import { fetchOrders } from "./api";
export function Orders() {
const { state, run } = useTask((signal) => fetchOrders(signal));
const load = (): void => {
run().catch((reason: unknown) => console.error(reason));
};
return (
<>
<button onClick={load}>Load</button>
<Match
on={state}
Idle={() => undefined}
Loading={() => <p>Loading…</p>}
Failed={({ error }) => <p>{error.message}</p>}
Ready={({ value }) => value.map((order) => <p key={order.id}>{order.total}</p>)}
/>
</>
);
}useTask also aborts the previous run when a new one starts (a second click), and the run in progress when the component unmounts.
The flag is a state set to a true/false literal (setLoading(true), setLoading(false)), declared with const [loading, setLoading] = useState(...). Any setter called after the await counts as one of the other states.
What the rule can't see: states set in .then(...) callbacks instead of after await, setters of useReducer or of a store, and states set by another function the first one calls.