TypeError: data.map is not a function in React JS / How to fix this issue
Answer How to fix this issue? TypeError: data.map is not a function in React JS
Following is sample code.
const [data, setData] = React.useState([])
React.useEffect(() => {
Axios.get('http://localhost:3001').then(res => {
setData(res)
}).catch(err => console.log(err))
}, [])
return (
<div className="container mx-auto">
{data.map(d => (
<h1>{d.name}</h1>
))}
</div>
)
Answer
data.map is not function error is happening because .map function
can be applied only on lists. Make sure your response is a list.
If you are not sure, what kind of response you are getting,
you can log it or inspect it.
In the above problem description, you are using axios to fetch
the API data and to get the data from the API you need to change it as
setData(res.data)