TypeError: data.map is not a function in React JS
I have a state called data
which is an empty list by default.
I am fetching data from an API and update the data state with the response JSON.
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>
)
But in the browser, I am getting an error saying
TypeError: data.map is not a function. How to fix this issue?
1 Answer
4 years ago by Divya
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)
4 years ago by Divya