dandrok
dandrok

Reputation: 27

fetch data react .map is not a function

Why does this code give me: TypeError: items.map is not a function?

  const [items, setItems] = useState([])

  const url = 'https://rickandmortyapi.com/api/character/1'

  useEffect(() => {
    async function fetchEmployees() {
      const response = await fetch(url)
      const fetchedEmployees = await response.json(response)
      setItems(fetchedEmployees)
    }
    fetchEmployees()
  }, [])

  return (
    <div>
      {items.map((element) => (
        <li>{element.name}</li>
      ))}
    </div>
  )
}

Upvotes: 0

Views: 983

Answers (2)

Siddhant Varma
Siddhant Varma

Reputation: 594

You don't need to pass the response inside response.json().

useEffect(() => {
    async function fetchEmployees() {
      const response = await fetch(url)
      const fetchedEmployees = await response.json()
      setItems(fetchedEmployees)
    }
    fetchEmployees()
  }, [])

Since your API doesn't return an array, you can't use map on items . The following should do

return (
    <div>
        <li>{items.name}</li>
    </div>
  )

If you're trying to fetch an array of objects, you should probably check another endpoint that returns an array of characters like this https://rickandmortyapi.com/api/character. You can then map through items.results to output the name inside your component's JSX.

Upvotes: 1

Bao Huynh
Bao Huynh

Reputation: 1054

I saw two problems in your code.

Firstly, the API link "https://rickandmortyapi.com/api/character/1" returns an object, not an array. You cannot use map for object, as map is an Array function. Recheck the URL of the API and adjust your code accordingly to match the shape of your value.

Secondly, for your fetchEmployees() function, you only need const fetchedEmployees = await response.json()

In cases like this, you are encouraged to use "print debugging" - putting console.log all over the place to get the idea of what is the internal working. For example, you can put a console.log here to see what you are getting (an object) and you should understand why map is not working on it

async function fetchEmployees() {
      const response = await fetch(url);
      const fetchedEmployees = await response.json();
      console.log("fetchedEmployess", fetchedEmployees);
      setItems(fetchedEmployees)
    }
``

Upvotes: 2

Related Questions