Every time I click on an element call the handleUpdateCanvasCards() function the textArray clears and the new element is added. I'm trying to use the spread operator to build up an array of elements based on user clicking but it keep clearing. Not sure if it is the useEffect() that is breaking things?
function App() {
const [textArray, setTextArray] = useState<string[]>([]);
const [data, setData] = useState<any[]>([]);
function handleClick(option: Option) {
setSelected(option);
}
[...]
function handleUpdateCanvasCards(info: string) {
setTextArray([...textArray, info]);
}
useEffect(() => {
if (selected === "Phonics") {
const phonicsData = spellingData.map((w: Spelling, i: number) => {
return (
<div
onClick={() => handleUpdateCanvasCards(w.spelling)}
key={i}
>
<h1>{w.spelling}</h1>
);
})}
</div>
</div>
);
});
setData(phonicsData);
}
if (selected === "Morphology") {
const morphemes = morphemeData.map((m: Affix, i: number) => {
return (
<div
onClick={() => handleUpdateCanvasCards(m.affix_name)}
key={i}
>
<h1>{m.affix_name}</h1>
</div>
);
});
setData(morphemes);
}
}, [selected]);
[...]
export default App;