Home > Software engineering >  TypeError: Cannot read properties of undefined (reading 'anwsers')
TypeError: Cannot read properties of undefined (reading 'anwsers')

Time:11-03

I don't know why I can't iterate the array objects state in React.

How i iterate:

{all.map(item =>
   <div>
    {item.anwsers.map(item_2 => <h3>{item_2.isCorrect && item_2.anwser}</h3>)}
       <p>{item.question}</p>
   </div>
)}

How i fill it?

useEffect(() => {
        var seperate = questions[currentQuestion -1];
        setAll([...all, seperate])
    }, [currentQuestion])

Here is the array all:

console.log

The error message I'm getting: error In react

CodePudding user response:

add ? before the item to wait the useEffect. Example: item?.anwsers.map...

CodePudding user response:

You can use the filter() method for removing undefined elements

{all.filter(a => a !== undefined).map(item =>
  <div>
    {item.anwsers.map(item_2 => item_2.isCorrect && <h3>{ item_2.anwser}</h3>)}
    <p>{item.question}</p>
  </div>
)}

CodePudding user response:

A simple way is to remove all falsy element values in your array:

{all.filter(Boolean).map(item =>
   <div>
    {item.anwsers.map(item_2 => <h3>{item_2.isCorrect && item_2.anwser}</h3>)}
       <p>{item.question}</p>
   </div>
)}

This way will removes all these values:

  1. empty string
  2. false
  3. 0
  4. null
  5. undefined

Note: Use this solution if your Array's elements are just array, object or none-falsy values.

  • Related