I Know It
Flashcards are there to find out which words you know. Under the card, the app gets two more buttons: Not yet and I know it. Both move on to the next card, and I know it also remembers that you know the word.
What does the app remember? Not the whole words, just their ids: the state known is an array of numbers, such as [2, 5], empty at first. As you know from the State lesson, an array in state is never changed in place (push() wouldn't change anything on the page). You make a new array instead, with spread to add an id and with filter() to remove one:
setKnown((known) => [...known, card.id]);
setKnown((known) => known.filter((id) => id !== card.id));Clicking I know it twice on the same card mustn't put its id into the array twice, so add it only if known.includes(card.id) is false.
The score above the card, Known: 2 of 12, is computed again: known.length of words.length. Because it's computed from the state on every render, it's always right.
The new buttons move on by calling handleNext(). But unlike Next, they aren't disabled on the last card, so handleNext() has to check for itself that there is a next card:
function handleNext() {
if (index < words.length - 1) {
setIndex((index) => index + 1);
}
}Without the check, I know it on the last card would move index past the end of the deck, words[index] would be undefined, and the app would stop with a TypeError: there's no card there to show.
Instructions
Add the state known, an empty array at first. Under the nav div, add <div className="answers"> with the button I know it. Its handler handleKnow() adds the card's id to known if it isn't there yet, and then calls handleNext(), which gets the check from above. Above the card, show <p className="score">Known: {known.length} of {words.length}</p>.
Before I know it, add the button Not yet. Its handler handleNotYet() removes the card's id from known (in case you clicked I know it by mistake) and also moves on with handleNext().