Last active
September 27, 2021 19:09
-
-
Save akatakritos/ff0d5c3454c14bdd2afa17871abf0e2c to your computer and use it in GitHub Desktop.
Pattern for tracking loading states. Demo of typescript discriminated union
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
export type LoadingStatus = 'idle' | 'loading' | 'fulfilled' | 'rejected'; | |
export type LoadingState<T, E = Error> = | |
| { state: 'idle' } | |
| { state: 'loading' } | |
| { state: 'fulfilled'; data: T } | |
| { state: 'rejected'; error: E }; | |
export const LoadingStates = { | |
idle<T, E = Error>() { | |
return { state: 'idle' } as LoadingState<T, E>; | |
}, | |
pending<T, E = Error>() { | |
return { state: 'loading' } as LoadingState<T, E>; | |
}, | |
fulfilled<T, E = Error>(data: T) { | |
return { state: 'fulfilled', data } as LoadingState<T, E>; | |
}, | |
rejected<T, E = Error>(error: E) { | |
return { state: 'rejected', error } as LoadingState<T, E>; | |
}, | |
map<TSource, TOutput, E = Error>(source: LoadingState<TSource, E>, f: (a: TSource) => TOutput): LoadingState<TOutput, E> { | |
if (source.state === 'fulfilled') { | |
return { state: 'fulfilled', data: f(source.data) }; | |
} else { | |
return source as LoadingState<TOutput, E>; | |
} | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment