I am trying to get a list of users from API and then use map
on every user to print the name, but I am not able to use it on the data.
I tried many different things and solutions on the internet but now it has been an hour and I can’t fix this. Please help in solving this
import "./App.css"
import useSWR from "swr"
function App() {
const fetcher = (...args) => fetch(...args).then((res) => res.json())
const { people } = useSWR(
"https://jsonplaceholder.typicode.com/users",
fetcher,
{ suspense: true }
)
return (
<div>
{people.map((person) => {
<div>{person.name}</div>
})}
</div>
)
}
export default App
I am using fetch
and I did check if I am getting something in return or not and YES I am getting the data but can’t use map
on it.
2
Answers
The issue is in the way you are using the
.map
function, here in your example it does not return anything, you have to use either an implicit return=>(...)
or an explicit return
=>{return(...)}
Note also that every child should have a unique
key
prop and better to map throughpeople
only when it is defined:This is likely because you are trying to map
people
before it has been fetched initially.You can do 1 of two things to combat this:
OR
These just check to make sure
people
actually has a value before it tries tomap
it and it won’t throw an error if it’s undefined.