Skip to content

Instantly share code, notes, and snippets.

@Cloudo
Created March 6, 2018 15:20
Show Gist options
  • Save Cloudo/144ae978364f075e6825e745c567d90d to your computer and use it in GitHub Desktop.
Save Cloudo/144ae978364f075e6825e745c567d90d to your computer and use it in GitHub Desktop.
fetch jsx
/* @flow */
import { handleActions, createAction } from 'redux-actions'
import { createNamedWrapperReducer } from 'utils/reducers'
const prefix = 'fetch'
/**
* FLOWTYPES
*/
export type Actions<Payload> = {
fetchStarted(): createAction<string, void, Function>,
fetchSuccess(payload: Payload): createAction<string, Payload, Function>,
fetchFailure(err: string): createAction<string, string, Function>,
}
export const types = {
FETCH_STARTED: `${prefix}/FETCH_STARTED`,
FETCH_SUCCESS: `${prefix}/FETCH_SUCCESS`,
FETCH_FAILURE: `${prefix}/FETCH_FAILURE`,
}
export type FetchReducer<Payload> = {
isFetching: boolean,
isFetched: boolean,
payload: Payload,
errorMessage: ?string,
}
const fetchReducer = handleActions(
{
[types.FETCH_STARTED]: state => ({
...state,
isFetching: true,
isFetched: false,
}),
[types.FETCH_SUCCESS]: (state, { payload }) => ({
...state,
isFetching: false,
isFetched: true,
payload,
}),
[types.FETCH_FAILURE]: (state, { payload }) => ({
...state,
isFetching: false,
isFetched: true,
errorMessage: payload,
}),
},
{
isFetching: false,
isFetched: false,
payload: null,
errorMessage: null,
}
)
const getFetchReducer = (name: string) =>
createNamedWrapperReducer(fetchReducer, name)
export default getFetchReducer
export const actions = (name: string) => ({
fetchStarted: createAction(types.FETCH_STARTED, undefined, () => ({ name })),
fetchSuccess: createAction(types.FETCH_SUCCESS, undefined, () => ({
name,
})),
fetchFailure: createAction(types.FETCH_FAILURE, undefined, () => ({
name,
})),
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment