-1

How can I pass fetched data to array called users? I've tried using this.users = data.data, then console.log(users) and nothing is showing up.

Also I am trying to map response, I am getting error in console Uncaught TypeError: fetchData.map is not a function

const users = [];

const fetchData = () => {
    axios.get('https://reqres.in/api/users')
  .then(({data}) => {
    this.users = data.data;
    console.log(data);
  })
}
fetchData();

const mapUsers = fetchData.map((item) => {
    return {
        avatar: item.avatar
    }
})

Dave
  • 1
  • 1
  • 9
  • 38
  • 3
    `users.push(data)` And you can't `map` over a function. `map` is an array method. – jmargolisvt Nov 06 '20 at 15:14
  • additionally, this: [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Randy Casburn Nov 06 '20 at 15:21
  • This is a bit of a mess. What is the data you're getting from /api/users? What is the expected result and the actual result, besides the error you're getting? – Technoh Nov 06 '20 at 15:22
  • I do nto get an error from fetching data. I have error when trying to map fetchData – Dave Nov 06 '20 at 15:39

1 Answers1

1

May be you would need to move map inside to the callback

let users = [];

const fetchData = () => {
  axios.get("https://reqres.in/api/users").then(({ data }) => {
    users = data.data;

    const mapUsers = users.map((item) => {
      return {
        avatar: item.avatar,
      };
    });
    console.log("mapUsers", mapUsers);
  });
};

fetchData();

or

let users = [];

const fetchData = () => {
  return axios.get("https://reqres.in/api/users").then(({ data }) => {
    return data.data;
  });
};

fetchData().then((data) => {
  console.log(data);
  const mapUsers = data.map((item) => {
    return {
      avatar: item.avatar,
    };
  });

  console.log("mapUsers", mapUsers);
});
Lashan Fernando
  • 1,187
  • 1
  • 7
  • 21