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
You have a problem with the scope.
users
is declared inside thetry
block, so you can’t reference it outside it. If you use it within thetry
block, you should be OK. E.g.:You don’t need to use try to catch error