skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    const [answerLines, setAnswerLines] = useState<object[]>([{
            id:0,
            answerText:"text answer 1",
            isCorrect:false
    
        },
        {
            id:1,
            answerText:"text answer 2",
            isCorrect:false
    
        }
    

    function passed as props for deleting

    const deleteAnswerLine = (index: number) => {
            setAnswerLines(answerLines.filter((item) => item.id !== index));
          };
    
    

    displaying the data as components

     {answerLines.map(item=><NewTestAnswerLine isCorrect={item.id===correctAnswer}  setCorrectAnswer={setCorrectAnswer} lineIndex={item.id} key={item.id} deleteLine={()=>deleteAnswerLine(item.id)}/>)}
    
    

  2. You need to refactor the deleteAnswerLine function and use the callback version of the state setter to avoid stale state:

    From:

    const deleteAnswerLine = (index: number) => {
      setAnswerLines(answerLines.filter((item) => item.props.lineIndex !== index));
    };
    

    To:

      const deleteAnswerLine = (index: number) => {
        setAnswerLines(answerLines => answerLines.filter((item) => item.props.lineIndex !== index));
      };
    

    References

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search