TypeScript Network Types
A TypeScript datatype representing network state which taking advantage of discriminated unions (or tagged unions, algebraic data types).
The Problem
When representing network state, the following data structure is commonly used:
var state = isFetching: true // whether we are fetching the data data: // the data we fetched error: {} // failed to fetch the data, but got an error
We may raise the following questions:
- What does it mean if
isFetching === true
anderror
field also exists? Refetching after failed? Can it mean something else? - What does it mean if all of the three fields exist?
- When rendering the UI, which field should I read first?
- How can I distinguish between initial page(not requested) and empty page(response with empty data)? by checking
data === null
ordata.length === 0
?
As we can see, it is hard to reason about by using this data structure, and it exists some impossible state.
A Solution
The above data structure is not a good model of the network state. Actually, network states are consist of:
- haven't start the request(
NotRequested
) - the request started, and haven't get the response yet(
Requesting
) - the request succeeded, responded with some data(
Succeeded
) - the request failed, responded with error(
Failed
)
And in some cases, we can refresh the data:
- refreshing by restart the request after succeeded(
Refreshing
) - refresh succeeded, got the new data(
RefreshSucceeded
) - refresh failed, got an error(
RefreshFailed
)
This is how this library trying to solve the problem. See the solution at the following Usage section.
Usage
// How to use the state to render UI
API
See https://vincentbel.github.io/ts-network.
FAQ
Why are there no RefreshSucceeded
state?
Because in common use case, after refreshing succeeded, we will rerender the UI with the new data we fetched, and turning the UI to Succeeded
state waiting for another refreshing. So, using Succeeded
state is enough.
If in your special case you need to store the previous data after refreshing succeeded, you should construct your own network state. like
Thanks
This library is largely inspired by the post How Elm Slays a UI Antipattern. And the talk Making Impossible States Impossible is great to watch.
License
MIT.