I’ve put together a Codepen showing the sample usage of Redux (State Management) with network requests (via Axios HTTP Client) in the React framework.
For data gateway I’ve chose to use the REQ | RES – REST API tester.
See the Pen React + Redux + Axios by Lukasz Grela (@LukaszGrela) on CodePen.0
This setup is using the promise middleware, in the real project I’m using the redux-promise
dependency, but I wasnt able to find it for this pen so I’ve copied it from tutorial on Thinkster:
function isPromise(v) { return v && typeof v.then === 'function'; } const promiseMiddleware = store => next => action => { if (isPromise(action.payload)) { action.payload.then( res => { action.payload = res; store.dispatch(action); }, error => { action.error = true; action.payload = error.response.body; store.dispatch(action); } ); return; } next(action); };
This Pen also differs to real project in one more place, the store.dispatch
in the pen always returns the action object, but in the project compiled with webpack (babel) dispatch returns action object or Promise if the action object’s payload is a Promise.
In the project I could do the following chainging
store.dispatch(actionListUsers()).then(result => { console.log("response",result); store.dispatch(actionListUsersSuccess(result.payload.data.data)); });
but in the pen I had to access payload
directly
store.dispatch( actionListUsers().payload.then(result => { console.log("response", result); store.dispatch(actionListUsersSuccess(result.data.data)); }) )