2
\$\begingroup\$

I'd like to know there's a better code than I did.

interface AnswerProps{
  itemId: string;
  value: Array<string>
}

This code works like checkbox. If answers has a value, I try to put the same value again. It would be deleted like toggle.

const App = () => {
   const [answers, SetAnswers] = React.useState<AnswerProps[]>([]);

   /*

   */
   const handleAnswers = (value: string, answerIndex: number) => {
      let i = answers[answerIndex].value.indexOf(value);
      if(i === -1){
        setAnswers(answers.map((el: AnswerProps, index: number)=>{
          if(index === answerIndex) return {...el, value: el.value.concat(value);
          else return { ...el }
        }));
      }
   }

   (...)
}
```
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.