I am unsure what you are trying, but I would recommend to additionally use redux-thunk
middleware, to do that:
const doLogin = values => dispatch => axios.post(…)
//not sure if one needs that for axios,
//but for fetch that is required
.then(res => res.json())
.then(json => dispatch({
type: DO_LOGIN,
payload: json
}));
That way the action dispatch is actually refered until the request is finished and the resulting data is dispatched to the store.
That way you also handle errors like so:
const doLogin = values => dispatch => … //as above
//…
.catch(error => dispatch({
type: DO_LOGIN_ERROR,
error: true,
payload: error
}))
Additionally you can dispatch more actions so indicate the start of the request like so:
const doLogin = values => dispatch => {
dispatch({
type: DO_LOGIN_START
});
return axios.post(…)
.then(res => res.json())
.then(json => dispatch({
type: DO_LOGIN_SUCCESS,
payload: json
}))
.catch(err => dispatch(/*as above*/))
}
Please note that the action creator returns the promise, so in other places, where you trigger the action you can do:
doLogin({…}).then(data => callBack());
If you follow that way, it is much easier to in cooperate with redux-form
, if you are using that for your forms, what I would recommend to use, too.
You should be aware, that the within the response object, its data is exposed as stream. That means, you cannot read the data twice. Once res.json()
or res.body()
is called, the data of the response is »consumed« and cannot be accessed from the response object again.