0

I try to map data in react like

import React from 'react'
import axios from 'axios'
import {useEffect, useState} from 'react'

export default function Home() {
  const [data, setData] = useState([])
  useEffect(() => {
    axios.get('http://127.0.0.1:8000/api/books').then(res => {
      console.log(res.data)
            setData(res.data)
        }).catch(err => console.log(err))
    }, [])
  
  return (
    <div>
    
    {data.map(book => (
                <h1>{book.title}</h1>
            ))}
    </div>
  )
}

in console data show like

{data: Array(100)}
data
: 
(100) [{…}, {…}, {…}, {…}, {…}, ]
[[Prototype]]
: 
Object

the error is enter image description here how to solve this issue i try many ways but not working please help me

2 Answers 2

3

console.log(res.data) shows it has a data object which consists the array. So you should set like setData(res.data.data). Currently you are setting the object, which cannot be used with map

Sign up to request clarification or add additional context in comments.

Comments

1

You can see the console the data is {data: Array(100)}

so you need to update the state like

  setData(res.data.data)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.