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)
3
Answers
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
Well first off when you defined:
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:
Then it’s important to consider that the
async
function returns a promise so you’d have to use thethen
construct to await for itSo on the userData you should