Skip to content

Instantly share code, notes, and snippets.

@kodeFant
Last active June 5, 2021 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kodeFant/2def3e32daa41e5dbc6b9664bf001429 to your computer and use it in GitHub Desktop.
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
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);
}
}
@praveeno
Copy link

praveeno commented Jun 5, 2021

npm i -S gist:2def3e32daa41e5dbc6b9664bf001429

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment