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.
Syed Mushahid is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
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
}
}