Last active
September 19, 2022 18:01
-
-
Save Retsam/81528bc557c69decaa61195e8bd499ab to your computer and use it in GitHub Desktop.
Minimal data fetching LoadState
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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