My react is 18.2. I want to a child component receives 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(). because it show 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():
[
{ id:1, date: '2011-01-01T00:00:00.000Z' },
{ id:2, date: '2013-09-03T00:00:00.000Z' },
{ id:3, date: '2012-04-02T00:00:00.000Z' },
{ id:4, date: '2013-12-08T00:00:00.000Z' },
{ id:5, date: '2010-01-23T00:00:00.000Z' },
];
App.js:
import { Child } from './Child';
const Test = ()=>{
const [toChild,setToChild] = useState()
useEffect(() => {
const data = async () => {
const fetchedData = await fetched();
setToChild(fetchedData)
};
data();
}, []);
const test = ()=>{
setToChild(fetchedData)
}
}
return(<Child toChild={toChild}>)
Child.js:
const Child= ({ toChild }) => {
const data = toChild;
const getDate = data.map((item) => item.date);
CodePudding user response:
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:
import { useState, useEffect } from 'react'
import { Child } from './Child';
const Test = ()=>{
const [toChild,setToChild] = useState([])
useEffect(() => {
const data = async () => {
const fetchedData = await fetched();
setToChild(fetchedData)
};
data();
}, []);
return <Child toChild={toChild} />
CodePudding user response:
Jsx is already rendered before javascript in react even though you fetch the data from server but html already rendered to the browser.so add any loading component to that. toChild?:<div>loading</div>:<Child toChild={toChild}/>