0

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]] })

}

1 Answers1

0

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)
Gary B
  • 188
  • 1
  • 8
  • this is done but I want to add the questions and options with no duplicate values, in this scenario duplicate values are also push – Shubham Sanchela Aug 18 '21 at 12:10
  • This will help you avoid adding duplicates to your questions list`if (exam?.questions.every(x=> !(x['que']== que))){ //Answer }` – Gary B Aug 18 '21 at 12:31
  • And you can do something like this to remove duplicate options `let options = [item[0].options[1], item[0].options[2], item[0].options[3], item[0].options[4]] let optionsWithNoDuplicates = Object.keys(options.reduce((a,c) => ({...a,[c]: (a[c] || 0) + 1}),{})) const newQuestion = { question: que, answer: value, options: optionsWithNoDuplicates }` – Gary B Aug 18 '21 at 12:44