skip to Main Content

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


  1. 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 =>(...)

    {people.map((person) =>  
        <div>{person.name}</div>
    )}
    

    or an explicit return =>{return(...)}

    {people.map((person) => {
       return <div>{person.name}</div> 
    })}
    

    Note also that every child should have a unique key prop and better to map through people only when it is defined:

    {people && people.map((person, index) =>  
        <div key={index}>{person.name}</div> // better to use and 'person.id' or any other unique value as 'key'
    )}
    
    Login or Signup to reply.
  2. 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:

    {people && people.map((person) =>
        <div>{person.name}</div>
    )}
    

    OR

    {people?.map((person) =>
        <div>{person.name}</div>
    )}
    

    These just check to make sure people actually has a value before it tries to map it and it won’t throw an error if it’s undefined.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search