Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make child components use map() from App.js props data?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);

>Solution :

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} />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading