redux-fetcher v2.1.0
redux-fetcher
Really simple isomorphic fetch for Redux. Can be used in any Redux project that uses redux-api-middleware.
Recommended method for simple isomorphic HTTP data fetching in Roc.
Install
npm install --save redux-fetcherImport
import { createFetchAction, createFetchReducer } from 'redux-fetcher';Create your fetch actions using createFetchAction.
Create your fetch reducers using createFetchReducer.
Example Usage (HTTP GET)
The example illustrates requesting some data from the open Github API.
Define fetch identifier for this action
const FETCH_REPOS = 'repos';This can be any unique string that will identify your request and its corresponding key in the state tree.
Create action for fetching data
const fetchRepos = createFetchAction(
FETCH_REPOS,
'https://api.github.com/users/rocjs/repos'
);The action fetchRepos can then be used with dispatch() directly, or if using react-redux through mapDispatchToProps and used like normal in your React components.
Create fetch reducer for this action
The generated reducer will ensure that the state is updated according to the internal fetch actions.
const fetchReposReducer = createFetchReducer(FETCH_REPOS);When adding your reducer to Redux using combineReducers, it is important that the key is equivalent to the action/reducer identifier above:
const myReducers = combineReducers({
[FETCH_REPOS]: fetchReposReducer
});Done!
For the rest of this section we assume
const state = store.getState();After a successful dispatch of fetchRepos and its following actions your data will be in state.repos.payload along with state.repos.error and state.repos.loading. Some useful data like endpoint is also set to state.repos.meta. These can optionally be used to give a better user experience.
You can also pass in your own metadata.
How it works
When fetchAction is dispatched the following will happen internally:
- It will check if the
fetchshould take place at all (See options) - It dispatches an action named
REPOS_FETCH_PENDING - The
fetchReposReducerhandlesREPOS_FETCH_PENDINGand will set thestate.repos.loadingtotrue,state.repos.errortofalseandstate.repos.meta.endpointto the requested URL that is currently loading. - It (through
redux-api-middleware) performs an isomorphicfetchusing theurl. This operation is async, and what it does depends if the fetch fails or succeeds.
If fetch succeeds
- It dispatches an action named
REPOS_FETCH_SUCCESS. The response will be stored instate.repos.payload.state.repos.errorandstate.repos.loadingwill always be false after reducing a success. Againstate.repos.metawill provideendpoint, but also aresponseobject with some basic information.
If fetch fails
- It dispatches an action named
REPOS_FETCH_FAILURE.state.repos.payloadwill contain the errornameandmessage.state.repos.errorwill be set totrueandstate.repos.loadingwill be false after reducing an error.state.repos.metawill provideendpointandresponse.
Note: In case of a network-error, redux-api-middleware will dispatch another PENDING type action, but with error set to true. See https://github.com/agraboso/redux-api-middleware/pull/26. This is likely to change in redux-api-middleware 3.x.x.
API
fetchAction(id, url, options, meta)
id: string uniquely identifying your fetch operationurl: string containing url to fetchoptions: object
Default options:
{
force: false,
method: 'GET',
body: '',
headers: undefined,
credentials: undefined,
bailout: undefined
} - `force`: boolean, set to true if you wish to perform fetch even if you have data in your store already. Only applies if you do not override bail yourself.
- `method`: string, HTTP method to use in fetch.
- `body`: string, request body to use (only applies to non-GET and non-HEAD requests)
- `headers`: object, specify custom HTTP headers to use in your request
- `credentials`: string, `omit`, `same-origin`, `include`. Include cookies in request?
- `bailout`: function. Is always executed before performing a request and will abort if it evaluates to true.
Your custom options passed will be shallow-merged with the default.meta: object or function(action, state, res) that returns object
The provided meta will be shallow-merged with the default metadata.
fetchReducer(id)
id: string uniquely identifying your fetch operation
Default bail:
const cached = !!state[id].payload && !force;
return state[id].loading || cached;It will bail if it is already fetching data or if it already has data and is not forced.
Defining your own custom metadata
As mentioned in the API overview above we can enhance our resulting meta with additional data.
Examples
createFetchAction(FETH_REPOS, 'https://api.github.com/users/rocjs/repos', {}, { importantData: 'xyz'} );
orcreateFetchAction(FETH_REPOS, 'https://api.github.com/users/rocjs/repos', {}, () => { importantData: 'xyz'} );
This will result in the default metadata also containing importantData: 'xyz'