Last active
June 5, 2021 11:36
-
-
Save kodeFant/2def3e32daa41e5dbc6b9664bf001429 to your computer and use it in GitHub Desktop.
RemoteData for TypeScript. Read more about how to use this pattern here: https://driftercode.com/blog/slaying-a-ui-antipattern-with-typescript
This file contains hidden or 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 RemoteData<E, D> = | |
| { type: "NOT_ASKED" } | |
| { type: "LOADING" } | |
| { type: "FAILURE"; error: E } | |
| { type: "SUCCESS"; data: D }; | |
function foldRemoteData<R, E, D>( | |
remoteData: RemoteData<E, D>, | |
notAsked: () => R, | |
loading: () => R, | |
failure: (error: E) => R, | |
success: (data: D) => R | |
): R { | |
switch (remoteData.type) { | |
case "NOT_ASKED": | |
return notAsked(); | |
case "LOADING": | |
return loading(); | |
case "FAILURE": | |
return failure(remoteData.error); | |
case "SUCCESS": | |
return success(remoteData.data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
npm i -S gist:2def3e32daa41e5dbc6b9664bf001429