request-state
A simple immutable request-state container. Inpired by RemoteDatajs.
Install
npm install request-state
Motivation/Problem
Defining and displaying the state of a request is not that hard, but can be unnecessarily complicated.
const state = loading: true data: undefined const state = loading: false data: undefined error: undefined // Updating this state is boring and might be repeted several places in our applicationconst state = loading: false data: undefined error: undefined isSuccess: false isError: false
Solution
The solution is to have a state for all request-state scenarios. request-state
have four different states that can easily be updated and passed to your react-components:
- IS_NOT_ASKED - request not started
- IS_FETCHING - request started
- SUCCESS - request success. We got some data
- ERROR - the request went wrong
Example Usage with a redux reducer
someReducer.js
const RequestState = ;const FETCHING_DATA DATA_RECEIVED FAILED_TO_RECEIVE_DATA } = ; const defaultState = ; module { };
app.js
const App = React moduleexports = App
API
request-state
instances
Creating a const RequestState = ; const requestState = ; //with default state // with inital data. Will be merged with default stateconst requestStateSuccess = isSuccess: true data: 12 console // [1,2]
update state
Call one of these methods to update state and receive a new instance of requestState.
- `.success(dataObj)` : will return a with success status and set the - `.fetching()` : will return a with fetching state- `.error(errorObj)` : will return a with error state and set the error
checking the state
- `.isNotAsked()` // Request not started- `.isFetching()` // Fetching- `.isSuccess()` // Success. We got some data- `.isError()` // Error. We got an error
Get data and error
- `.getData()` : returns the data set with `.success(data)`- `.getError()` : returns the error set with `.error(err)`
Combine with other state
There is no problem combining the requestState instance with other state
const defaultState = isToggled: false requestState: