Skip to content

Instantly share code, notes, and snippets.

@kodeFant

kodeFant/remote-data.ts

Last active May 5, 2020
Embed
What would you like to do?
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.