In the Ultimate Redux Source code, go into bugs-backend project.
Install by typing npm i
then npm start
Now a node server should be running at localhost:9001
The approach
reducer should not make any outside manipulations, like DOM or calling APIS. It get current state, an d return new state. It should be pure.
Hence in our actionCreator, we can encapsulate code with side effects.
1 2 3 4 5 |
const actionCreator = () => { return (dispatch) => { } } |
1 2 3 4 5 |
const actionCreator = () => dispatch => { // call api // resolve: dispatch(success) // rejected: dispatch(error) } |
However, whenever we get data, we always call this actionCreator. It can get repetitive.
Middlware
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// action objects const action = { type: 'apiCallBegan' // apiRequest, payload: { url: '/bugs', method: 'get', data: {}, onSuccess: 'bugsReceived', onError: 'bugsRequestFailed } } const api = store => next => action => { if (action.type !== 'apiCAllBegan') { next(action); return; } }; export default api; |