skip to Main Content

When I use console.log(users) to fetch data asynchronously from API in nextJS, users data console.log(users) works successfully in the console, but when I return the mapping data, it says users.map() is not a function.

Below is the code:

async function getUsers(){
    const response = await fetch("http://localhost:3000/api/users");
    const data = await response.json();
    return data;
}

export default async function Page(){
    try{
        const users = await getUsers();
        console.log(users);
    }catch(error){
        console.log(error);
    }
    
    return(
        <div>
            <h1>List of users</h1>
            {
                users.map( (item) => {
                    {item.name}
                })
            }
        </div>
    )
}

output:

Unhandled Runtime Error
Error: users is not defined

Source
srcappuserspage.js (19:17) @ users

  17 |             <h1>List of users</h1>
  18 |             {
> 19 |                 users.map( (item) => {
     |                 ^
  20 |                     {item.name}
  21 |                 })
  22 |             }

I am trying to fetch user’s data from API to show the frontend.

2

Answers


  1. You have a problem with the scope. users is declared inside the try block, so you can’t reference it outside it. If you use it within the try block, you should be OK. E.g.:

    export default async function Page() {
        try{
            const users = await getUsers();
            console.log(users);
       
            return(
                <div>
                    <h1>List of users</h1>
                    {
                        users.map( (item) => {
                            {item.name}
                        })
                    }
                </div>
            )
        } catch (error) {
            console.log(error);
            // return some sensible default empty page here
        }
    
    }
    
    Login or Signup to reply.
  2. You don’t need to use try to catch error

    async function getUsers(){
    const response = await fetch("http://localhost:3000/api/users");
    const data = await response.json();
    return data;
    }
    
    export default async function Page(){
        const users = await getUsers();
    
        if(!users.ok){
        console.log("failed to fetch users data")
        }
    
    return(
        <div>
            <h1>List of users</h1>
            {
                users.map( (item) => {
                    {item.name}
                })
            }
        </div>
    )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search