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:
The error message I'm getting:
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:
- empty string
- false
- 0
- null
- undefined
Note: Use this solution if your Array's elements are just array, object or none-falsy values.