arraysreactjsduplicatesuse-statearrayofarrays

How do I not include duplicate values in a React state array , how to prevent duplication of values in array?


I want to store 15 different questions in items[0].question state

I want to make sure that I can't push a duplicated value into an array in a React state. The duplicated value is still going in the array though.

I have tried using .includes but it is not working.

const [exam, setExam] = useState({
    subjectName: "",
    questions: [

    ], notes: [
        ""
    ]
})

const [item, setItem] = useState([
    {
        question: "",
        answer: "",
        options: []
    }
])

const nextQuestion = (e) => {
    e.preventDefault()
    const que = item[0].question

    exam?.questions?.push({ question: que, answer: value, options: [item[0].options[1], item[0].options[2], item[0].options[3], item[0].options[4]] })

}

Solution

  • Because you are using setState, you will need to use setExam to update exam

    Something like:

    const newQuestion = { question: que, answer: value, options: [item[0].options[1], item[0].options[2], item[0].options[3], item[0].options[4]] }
    newExams = {...exam, questions: [...exam.questions, newQuestion ]}
    setExam(newExams)