Jayker
Jayker

Reputation: 5

What's the problem when trying to render the cards?

I'm trying to render multiple cards by pulling data from the API. But the return is an array, I don't understand why the map is not working.

const CharacterCard = () => {
  const [showModal, setShowModal] = useState(false)

  const openModal = () => {
    setShowModal(prev => !prev)
  }

  const characters = useRequestData([], `${BASE_URL}/characters`)

  const renderCard = characters.map((character) => {
    return (
      <CardContainer key={character._id} imageUrl={character.imageUrl} />
    )
  })

  return (
    <Container>
      {renderCard}
      <ModalScreen showModal={showModal} setShowModal={setShowModal} />
    </Container>
  )
}

export default CharacterCard

The hook is this

import { useEffect, useState } from "react"
import axios from "axios"

const useRequestData = (initialState, url) => {
  const [data, setData] = useState(initialState)

  useEffect(() => {
    axios.get(url)
      .then((res) => {
        setData(res.data)
      })
      .catch((err) => {
        console.log(err.data)
      })
  }, [url])

  return (data)
}

export default useRequestData

Console error:

console error image

Requisition return:

requisition return image

API: https://disneyapi.dev/docs

Upvotes: 0

Views: 67

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53884

If you notice the axios response schema, the data entry "is the response that was provided by the server".

Disney API response includes the data entry too.

Therefore, you actually wanted to get Disney data and not the axios response, fix it to:

setData(res.data.data)

You could debugged it by logging console.log(res) or going backward in the error chain console.log(characters) should result {data: [...]}, which hints that you can't execute .map on an object.

Upvotes: 2

Related Questions