Skip to content

Instantly share code, notes, and snippets.

@Retsam
Last active Dec 3, 2020
Embed
What would you like to do?
Minimal data fetching LoadState
type LoadState<T> =
| { state: "loading" }
| { state: "loaded", data: T }
// Not all usecases will have an error state, in which case it's fine to omit it here.
| { state: "error", err: string };
type ExamplePayload = string;
const ExampleComponent = () => {
const [ loadState, setLoadState ] = useState<LoadState<ExamplePayload>>({ state: "loading });
useEffect(() => {
apiCall()
.then(data => setLoadState({state: "loaded", data }))
.catch(err => setLoadState({state: "error", err: err.message}));
}, []);
if(loadState.state === "loading") {
return <LoadSpinner />;
}
if(loadState.state === "error") {
return <ErrorMessage message={loadState.err} />
}
const payload = loadState.data;
return <div>Hello {payload}</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment