Last active
May 6, 2016 12:29
-
-
Save christianalfoni/8edce0bf7f05bf00042d1246923838ab to your computer and use it in GitHub Desktop.
Redux ActionTree middleware
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
import {signal, dispatch} from 'redux-action-tree'; | |
import {SET_LOADING, SET_DATA, UNSET_LOADING, SET_ERROR} from 'constants'; | |
import getData from 'actions/getData'; | |
// Use a signal factory to create a signal | |
export default signal([ | |
// The dispatch factory allows you to easily dispatch actions. The current payload is always passed. | |
// Giving {type: "SET_LOADING", payload: {}} as action | |
dispatch(SET_LOADING), | |
// Use normal actions to do whatever you want. You can not dispatch on async actions | |
getData, { | |
success: [ | |
dispatch(SET_DATA) | |
], | |
error: [ | |
dispatch(SET_ERROR)] | |
}, | |
dispatch(UNSET_LOADING) | |
]); |
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
import { | |
SET_LOADING, | |
SET_DATA, | |
UNSET_LOADING, | |
SET_ERROR | |
} from 'constants'; | |
const initialState = { | |
isLoading: false, | |
data: null, | |
error: null | |
}; | |
// This works as normal | |
export default function(state = initialState, action) { | |
switch (action.type) { | |
case SET_LOADING: | |
return {...state, isLoading: true}; | |
case SET_DATA: | |
return {...state, data: action.payload.data}; | |
case UNSET_LOADING: | |
return {...state, isLoading: false}; | |
case SET_ERROR: | |
return {...state, error: action.payload.error}; | |
} | |
return state; | |
} |
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
// Dispatch is undefined in async actions | |
function getData({input, output, getState, dispatch}) { | |
axios.get('/data') | |
.then(response => output.success({data: response.result})) | |
.catch(error => output.error({error: error.message})); | |
} | |
getData.async = true; | |
export default getData; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment