Home > Back-end >  TypeError: null is not an object (evaluating 'daysData.map') - Trying to map over array of
TypeError: null is not an object (evaluating 'daysData.map') - Trying to map over array of

Time:12-25

Hope you're all doing good, I've tried looking around for a specific answer regarding this issue I'm having in ReactJS where I'm trying to map over an array I'm fetching via my local system and I keep getting this error in the console:

TypeError: null is not an object (evaluating 'daysData.map')

Here is a snapshot of my bit of code where I'm initializing the array from fetch: Fetched data to Array

And here it is in text format:

// Here I initalize the array with useState
  const [daysData, setDaysData] = useState(null);

  // Here is the port I'm fetching my array from.
  useEffect(() => {
    fetch('http://localhost:5001/chocolates')
      .then((resp) => resp.json())
      .then((data) => setDaysData(data));
  }, []);

  // Console logging is sending back the array with no issues
  console.log(daysData);

And here is the map function where I'm trying to render a with the 'id' key from the array:

Array.map not working

Here is the bit of code in text format:

{/* Here I'm getting the error " TypeError: null is not an object (evaluating 'daysData.map') " */}
      {daysData.map((day) => (
        <div>{day.id}</div>
      ))}

And here is an example of the array where I've fetched data from in which I'm trying to map over: Array and Objects Within

Thanks for any help in advance

CodePudding user response:

Just set the default state to an empty array instead of null so the Array.prototype.map() works on the initial render before the data is received.

The map() of the empty array won't produce anything in the rendered view

const [daysData, setDaysData] = useState([]);

CodePudding user response:

Your array is null on rendering, and your api fetches after rendering your web app so you need to set it conditionally like this

{daysData !== null? daysData.map((day) => <div>{day.id}</div>:null)}
  • Related