skip to Main Content

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


  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

    Login or Signup to reply.
  2. 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 };
    
    Login or Signup to reply.
  3. // **"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
    }); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search