1

I have a getAllUsers.js File, which fetched all the users from the API

import axios from 'axios'

export const fetchData = async () => {
  let response

  try {
    response = await axios.get('http://127.0.0.1:8000/api/users')
  } catch (e) {
    console.error(e.message)
  }

  return response?.data ? response?.data : null
}

In addition, I want to import this getAllUsers to the other pages. I tried this code, but it returns an error "TypeError: response.map is not a function"

import { fetchData } from '../../getAllUsers'

const response = fetchData()

const users = response.map(item => ({
  id: item.id,
  fullName: `${item.fname} ${item.lname}`,
  username: item.account.username,
  password: 'test',
  emal: item.email,
  role: 'admin'
}))

console.log(users)
  • `fetchData` is `async` you have to use `await` to get data out of it – Konrad Jun 19 '23 at 15:58
  • Does this answer your question? [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) – Konrad Jun 19 '23 at 15:58
  • 1
    btw, you can shorthand `response?.data ? response?.data : null` to `response?.data ?? null` – spender Jun 19 '23 at 16:04

3 Answers3

1

fetchData returns a promise for an array (or null), not the array itself.

At some point you need to materialize the promise by awaiting it (either with the await keyword in an async function, or by means of its .then() method.

To do this at the top level, you could

const usersPromise = fetchData().then((data) => data?.map(...))

but you'll still have a promise that will need to be awaited before consumption

spender
  • 117,338
  • 33
  • 229
  • 351
1

Well first off when you defined:

return response?.data ? response?.data : null

You are saying that the function could actually return null. So there are two options here: either you safely return an empty array to avoid errors (if you don't care that the API returned an error) or you throw an error and handle it when you call fetchData().

In your case I'd say you probably don't so you'll have to change the return type to:

return response?.data ? response?.data : []

Then it's important to consider that the async function returns a promise so you'd have to use the then construct to await for it

So on the userData you should

const users = [];

fetchData().then((data) => {
  users = data.map(item => ({
     id: item.id,
     fullName: `${item.fname} ${item.lname}`,
     username: item.account.username,
     password: 'test',
     email: item.email,
     role: 'admin'
  }));

export { users };
L_Cleo
  • 1,073
  • 1
  • 10
  • 26
0
// **"TypeError: response.map is not a function"
// This means response is not an array. which is due to the fact that u are not getting any response return from fetchData function.**

export const fetchData = async () => {
let response
 try {
 Here u are awaiting response as it is an asynchronous operation.
    response = await axios.get('http://127.0.0.1:8000/api/users')
  } catch (e) {
    console. Error(e.message)
  }
   and this is a synchronous code u are returning.
  return response?. Data ? response?. Data : null
}
Correct code -> 
export const fetchData = async () => {
  let response

  try {
    return await axios.get('http://127.0.0.1:8000/api/users')
  } catch (e) {
    console. Error(e.message)
  }
}

fetchData().then((res) => {
    // do ur thing
}); 
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 20 '23 at 14:21