Search code examples
reactjsapidictionaryaxios

TypeError: data.map is not a function in react


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


Solution

  • 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