How to solve array.map is not a function error in React?

1.6k Views Asked by At

I'm trying to map an array in a functional component. Array which is being stored as state and whose values are also being generated in the same component.

My approach in a summarized format:

import React, { useState , useEffect } from 'react'

const NewArray = () => {
  const [array, setArray] = useState([]);
  
  useEffect (() => {
    resetArray()
    
    //my debugging efforts
    console.log("Reset array is rendered")
    console.log(array)
  }, [])
  
  const resetArray = () => {
    const ary = [];

    for(let i=0; i<100; i++){
      ary.push(i);
    }

    setArray({ary});
    
    //Results posted below
    console.log("ary is pushed into the array")
    console.log(array)
  }
  
   return (
    <>
        {array.map((value, index) => (
          <div className='array-bar' key={index}>
            {value}
          </div>
        ))}
    </>
  )
}
    
    

First problem is, at times I get an array consoled logged with 100 elements. But most of the times when I reload I receive an empty array:

Times when I received 100 elements in array: [![Array(100)[1]][1]

Times when I received empty arrays:

[![[][2]][2]

I'm new with React, so my guess is that whenever you reload component doesn't get mounted i.e. maybe useEffect doesn't get executed. But if it was so, I wouldn't even receive the console.logs in first place. So maybe It does gets mounted but I can't think of any reason why it should return an empty array.

The second problem is the main question itself: [![error][3]][3]

Now I understand that we should pass a non-empty array to map. But even if an empty array gets passed, the error is

Uncaught TypeError: Cannot read property 'map' of undefined

Please tell me what am I doing wrong and what should I do to correct it. As well, if you can please mention it as a sidenote- in the second and third image why did the console.log and error resp. got fired twice?

Any help is very much appreciated.

Thank you [1]: https://i.stack.imgur.com/g3ENh.png [2]: https://i.stack.imgur.com/C0zKJ.png [3]: https://i.stack.imgur.com/NdwVW.png

1

There are 1 best solutions below

0
Mohamad Dahmardeh On

you should change setArray({ary}) to setArray(ary). when the setArray({ary}); runs, the Array state is no longer an array and becomes an Object which does not have the map method. try using TypeScript to avoid this type of problems.

 const resetArray = () => {
const ary = [];

for(let i=0; i<100; i++){
  ary.push(i);
}

setArray(ary);
}