My react is 18.2. I want the child component to receive data and use map() from App.js.
I checked the child component received the data, but I don’t know why does it can’t use map().
It shows this error.
Uncaught TypeError: Cannot read properties of undefined (reading 'map')
So do anyone can fix it? I guess this is render problem, but I don’t know how to fix it, thank you.
fetched():
JavaScript
x
8
1
[
2
{ id:1, date: '2011-01-01T00:00:00.000Z' },
3
{ id:2, date: '2013-09-03T00:00:00.000Z' },
4
{ id:3, date: '2012-04-02T00:00:00.000Z' },
5
{ id:4, date: '2013-12-08T00:00:00.000Z' },
6
{ id:5, date: '2010-01-23T00:00:00.000Z' },
7
];
8
App.js:
JavaScript
1
19
19
1
import { Child } from './Child';
2
3
const Test = () => {
4
const [toChild, setToChild] = useState()
5
useEffect(() => {
6
const data = async () => {
7
const fetchedData = await fetched();
8
setToChild(fetchedData)
9
};
10
data();
11
}, []);
12
13
const test = () => {
14
setToChild(fetchedData)
15
}
16
}
17
18
return(<Child toChild={toChild}>)
19
Child.js:
JavaScript
1
6
1
const Child = ({ toChild }) => {
2
const data = toChild;
3
4
const getDate = data.map((item) => item.date);
5
6
Advertisement
Answer
Since the data coming from your fetch is an array of objects, you may want to initialize the state as an empty array useState([])
, useEffect
will fire once the component has been mounted so at first, toChild
will be undefined
and that’s why you are getting that error.
So basically:
JavaScript
1
16
16
1
import { useState, useEffect } from 'react'
2
import { Child } from './Child';
3
4
const Test = ()=>{
5
const [toChild,setToChild] = useState([])
6
7
useEffect(() => {
8
const data = async () => {
9
const fetchedData = await fetched();
10
setToChild(fetchedData)
11
};
12
data();
13
}, []);
14
15
return <Child toChild={toChild} />
16