I have an array of JavaScript objects that I holding in React State, and on a click, I change the property of one of the objects in the array.
I got the following to work without mutating state, but my current setState()
syntax also adds the same object to the end of the array again.
How can I simply change the state of one of the objects in my array of objects in state, without adding another object and without mutating state?
import React, { useState } from 'react';
interface IFlashcard {
noun: string;
article: string;
show: boolean;
}
const initialFlashcards = [
{
noun: 'Dependency',
article: 'die Dependency, die Dependencys',
show: false
},
{
noun: 'Kenntnis',
article: 'die Kenntnis, die Kenntnisse',
show: false
},
{
noun: 'Repository',
article: 'das Repository, die Repositorys',
show: false
},
{
noun: 'Kenntnis',
article: 'die Kenntnis, die Kenntnisse',
show: false
}
];
function LanguageFlashcards() {
const [flashcards, setFlashcards] = useState(initialFlashcards);
const toggleFlashcard = (flashcard: IFlashcard) => {
flashcard.show = !flashcard.show;
setFlashcards([...flashcards, flashcard]);
}
return (
<>
<h2>Language Flashcards</h2>
<ul>
{flashcards.map((flashcard: IFlashcard) => {
return (
<>
<li><span onClick={() => toggleFlashcard(flashcard)}>{flashcard.noun}</span>
{flashcard.show && (
<>
: {flashcard.article}
</>
)}
</li>
</>
)
})}
</ul>
</>
);
}
export default LanguageFlashcards;