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 can I solve map function problem in ReactJS?

I am fetching data and I am passing props to other components. But in one of the child components I can’t using map() function. I am getting Cannot read properties of undefined (reading ‘map’). I think this is an asynchronous data problem. But I can’t solve it.

Here is my child component:

function WeeklyForecast({data}) {

      console.log(data);
      
      return (
        <div className='WeeklyForecast'>
          <div className="Prev-Btn">
            <button>&lt;</button>
          </div>
          <div className="Forecast-List">
          {data.map((forecast, index) => (
              <div key={index}>
    
                <p>{forecast[0]}</p>
    
              </div>
            ))}
          </div>
          <div className="Next-Btn">
            <button>&gt;</button>
          </div>
        </div>
      )

}

There are my error and browser console results without map() function:

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

enter image description here

enter image description here

>Solution :

So the problem you are facing is you are trying to map over the data before it becomes available (as per your logs) what you want to do is make sure the data is available before blindly mapping over it… You can do such by checking that the data is available. You can learn more about conditional rendering here.

Just add a && (AND) clause to your statement, so that you can guarantee that data is not undefined and available.
This will give you the ability to wait for the data to load from your server.
So the statement becomes data && data.map(...)
So your code will look like the following.

function WeeklyForecast({data}) {

      console.log(data);
      
      return (
        <div className='WeeklyForecast'>
          <div className="Prev-Btn">
            <button>&lt;</button>
          </div>
          <div className="Forecast-List">
          {data && data.map((forecast, index) => (
              <div key={index}>
    
                <p>{forecast[0]}</p>
    
              </div>
            ))}
          </div>
          <div className="Next-Btn">
            <button>&gt;</button>
          </div>
        </div>
      )

}
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