Skip to content

Instantly share code, notes, and snippets.

@christianalfoni
Last active May 6, 2016 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianalfoni/8edce0bf7f05bf00042d1246923838ab to your computer and use it in GitHub Desktop.
Save christianalfoni/8edce0bf7f05bf00042d1246923838ab to your computer and use it in GitHub Desktop.
Redux ActionTree middleware
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)
]);
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;
}
// 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