timo.js
timo.js

Reputation: 92

Pushing Data into empty Array - React useState() Hook

I want to declare an empty State for wrong answers in my Quiz-App like this:

const [wrongAnswers, setWrongAnswers] = useState();

But if I try to fill it up with data (I want to make it an Array of Objects) it always return undefined. I try it like this:

    const getWrongAnswers = () => {
    const result = birds.filter((bird) => bird.status === "wrong");

    setWrongAnswers([...wrongAnswers, result]);
  };

If i declare my state as an empty Array it'll always give me an empty Array, same with an emptry Array of Objects.

I don't know what I am missing here.

Upvotes: 2

Views: 5749

Answers (1)

MORÈ
MORÈ

Reputation: 2580

You initialise it with empty array while declaring.

const [wrongAnswers, setWrongAnswers] = useState([]);

and filter returns array so use spread operator instead of just result

setWrongAnswers([...wrongAnswers, ...result]);

Upvotes: 2

Related Questions