Skip to content
Advertisement

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

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():

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

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:

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} />
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement