. Advertisement .
..3..
. Advertisement .
..4..
Hello, everyone! I’m back here. I am in trouble with the typeerror: ”typeerror: cannot read property ‘map’ of undefined” and I don’t know how to fix it? This is program which I run:
function MyComponent() {
const [data, setData] = useState();
useEffect(() => {
fetch('/api/data')
.then((res) => res.json())
.then((data) => {
setData(data);
})
.catch((err) => {
console.log(err);
});
}, []);
return (
<ul>
{data.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
Then I get an error:
Cannot read property 'map' of undefined
This is my final exam question, it’s very urgent. Please help me. Thanks!
The cause:
After looking over your progarm, I found that you didn’t give original value to
data
in youruseState
hook, sodata
is . Before React firstly showed your JSX, it didn’t wait for fetching data or asynchronous action occured. To put it simply, React was attempting to run data.map(…) while the data was being fetched. Therefore, the error: ”Cannot read property ‘map’ of undefined” appeared.Solution:
While you are waiting for your fetching data, you need to set your variable state to an array. If you do this, the map method will appear on an empty data array when React call. And anything is not shown and the error will not happen. When the data is loaded from the API call, your data state will be installed and your list will shows correctly. Let’s follow my program:
I hope you can fix your error with my suggestion.