The below code for an asynchronous action works does not work, i.e, the fetch works fine but the dispatch doesn’t work. (Please see the output in the codesandbox link at the bottom.)
function addUser(user) {
return {
type: FETCH,
payload: { user }
};
}
// action creator returns a function
export function fetchUser(githubUserName) {
console.log("fetching...");
return (dispatch) => {
return axios(`https://api.github.com/users/${githubUserName}`).then(
(user) => {
// dispatch(addUser(user.data));
let res = user.data;
dispatch({
type: FETCH,
payload: { res }
});
}
);
};
}
If I uncomment the dispatch(addUser(user.data));
and comment the below part
let res = user.data;
dispatch({
type: FETCH,
payload: { res }
});
It works. I’m unable to get why the former does not work. Is there a way to make my dispatch work without using dispatch(addUser(user.data))
?
Link to codesandbox : https://codesandbox.io/s/fetch-with-redux-thunk-no-connect-used-jy5c77?file=/src/actions/fetch.js
2
Answers
The
addUser
action creator function returns an action object with type"FETCH"
and apayload
property object with auser
property.The
dispatch(addUser(user.data));
call is working. Where the other code differs is in what is stored in the action payload.Here you’ve hardcoded the action object with the same
type
property, but thepayload
property object has ares
property. Change this touser
and it also works.Code
I checked your codelines. It has one problem.
dispatch({
type: FETCH,
payload: { user: user.data }
});
you have to change like this.