Search code examples
node.jsreactjsreduxfetch-apinode-fetch

how to properly replace axios api with fetch api and map over the received data in nodeJS?


this is the link of the entire file - asyncActions.js

the part with axios api -

const fetchUsers = () => {
  return function (dispatch) {
    dispatch(fetchUsersRrequest());
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then((res) => {
        // res.data is the array of users
        const users = res.data.map((user) => user.id);
        dispatch(fetchUsersSuccess(users));
      })
      .catch((error) => {
        // error.message gives the description of message
        dispatch(fetchUsersFaliure(error.message));
      });
  };
};

Function Output -

{ loading: true, users: [], error: '' }
{
  loading: false,
  users: [
    1, 2, 3, 4,  5,
    6, 7, 8, 9, 10
  ],
  error: ''
}

replacing the part with fetch api -

    const fetchUsers = () => {
  return function (dispatch) {
    dispatch(fetchUsersRrequest());
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((res) => {
        const users = res.json().map((user) => user.id);
        console.log(users);
        dispatch(fetchUsersSuccess(users));
      })
      .catch((error) => {
        dispatch(fetchUsersFaliure(error.message));
      });
  };
};

the OUTPUT -

{ loading: true, users: [], error: '' }
{
  loading: false,
  users: [],
  error: 'res.json(...).map is not a function'
}

what am I doing wrong ? why can't I map over the data ?


Solution

  • Call res.json() will return a Promise. You need to add a second then block:

    fetch("https://jsonplaceholder.typicode.com/users")
    .then((res) => res.json())
    .then((res) => {
       const users = res.map((user) => user.id);
       console.log(users);
       dispatch(fetchUsersSuccess(users));
     })
    .catch((error) => {
       dispatch(fetchUsersFaliure(error.message));
    });