Skip to content

Instantly share code, notes, and snippets.

@Retsam
Last active September 19, 2022 18:01
Show Gist options
  • Save Retsam/81528bc557c69decaa61195e8bd499ab to your computer and use it in GitHub Desktop.
Save Retsam/81528bc557c69decaa61195e8bd499ab to your computer and use it in GitHub Desktop.
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