I have a state array using useState that keeps track of some components, I add components to the array with a click of a button i.e
const [answerLines, setAnswerLines] = useState<any[]>([]);
adding to the array
const addAnswerLine = () => {
setAnswerLines([
...answerLines,
<NewTestAnswerLine
key={answerLines.length}
lineIndex={answerLines.length}
isCorrect={answerLines.length === correctAnswer}
setCorrectAnswer={setCorrectAnswer}
deleteLine={() => deleteAnswerLine(answerLines.length)}
/>,
]);
};
when it comes deleting the lines by filtering out the array of the clicked line Id, it doesn’t work as expected, for instance if I click the 0 index item the array filters to null.
This is my delete function that I pass down through props:
const deleteAnswerLine = (index: number) => {
setAnswerLines(answerLines.filter((item) => item.props.lineIndex !== index));
};
2
Answers
following the advice from comments and changing tactic, saving the data on the state and using the state to map the array to components for display, this made it easier to manage and now the above functions work as intended.
example:
function passed as props for deleting
displaying the data as components
You need to refactor the
deleteAnswerLine
function and use the callback version of the state setter to avoid stale state:From:
To:
References