Search code examples
javascriptreactjsarraysjavascript-objects

Exporting Axios Response using React JS


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)

Solution

  • 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