skip to Main Content

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


  1. The addUser action creator function returns an action object with type "FETCH" and a payload property object with a user property.

    function addUser(user) {
      return {
        type: FETCH,
        payload: { user }
      };
    }
    

    The dispatch(addUser(user.data)); call is working. Where the other code differs is in what is stored in the action payload.

    let res = user.data;
    dispatch({
      type: FETCH,
      payload: { res }
    });
    

    Here you’ve hardcoded the action object with the same type property, but the payload property object has a res property. Change this to user and it also works.

    let res = user.data;
    dispatch({
      type: FETCH,
      payload: { user: res }
    });
    

    Code

    export function fetchUser(githubUserName) {
      return async (dispatch) => {
        const { data } = await axios(
          `https://api.github.com/users/${githubUserName}`
        );
        dispatch({
          type: FETCH,
          payload: { user: data }
        });
      };
    }
    

    Edit react-redux-thunk-why-is-my-async-action-not-working

    Login or Signup to reply.
  2. I checked your codelines. It has one problem.
    dispatch({
    type: FETCH,
    payload: { user: user.data }
    });

    you have to change like this.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search