My goal is to create a React.js app that cycles through flashcards in a random order.
To do this, I have a set declared to hold previously stored cards and a function to cycle through cards. However, after adding elements to the set in a function, none of the elements are retained once the function is called again.
App.jsx
import React from "react";
import { useState } from "react";
import FlippableCard from './components/flippable-card.jsx'
// import
const App = () => {
const cards = [{question: "2+2", answer: "4"}, {question: "3+2", answer: "5"}, {question: "4+5", answer: "9"}]
var reviewedCards = new Set([])
const [card, setCard] = useState(0)
// Optimize this later
const changeCard = (reviewedCards) => {
var newCard = card
// console.log(reviewedCards.size, cards.length)
// if (reviewedCards.size == cards.length) {
// reviewedCards.clear()
// }
console.log(reviewedCards.size)
reviewedCards.add(card)
console.log(reviewedCards.size)
let text = "";
for (var entry of reviewedCards.values()) {
text += entry;
}
console.log("Set " + text)
while (reviewedCards.has(newCard)){
newCard = Math.floor(Math.random()*cards.length);
}
setCard(newCard)
// console.log(newCard)
reviewedCards.add(newCard)
console.log(reviewedCards.size)
}
return (
<div className="app">
<FlippableCard front={cards[card].question} back={cards[card].answer}/>
<button onClick={changeCard}></button>
</div>
)
}
export default App
I ran the function once and the end result was a set populated with 3 elements. After running the function again, the set started off with 0 elements again rather than retaining a size of 3. I suspect it to be an issue with the scope of the set.
The value is re-declared on every render. You need to store the value in state, exactly like you already do with your other state value.
Your changeCard function is written to accept reviewedCards as a parameter (instead of using the global reviewedCards variable). Because you don’t pass any parameter when you call it, reviewedCards within the function is going to be undefined.
Thank you. I have updated the code accordingly.