Storing clicked checkboxes (labels) in an array.
Hello everyone, I'm working with Formik to create group of checkboxes for my Survey page. Now the idea is to place each checked label in an array which named "answers" and when press submit button I want to get those clicked answers as a printout in the console.log for now. Well, issue is that when I first click on any label that first one doesn't placed in array but every next one I clicked stored in an array. It is not clear to me for what reason the first clicked does not do the same? Maybe the cause is the order in the code, at which point which part of code is rendered on the page. I hope I explained the problem well, all suggestions are welcome. This is what the onClick function looks like and I also send the rest of the code, I have two files, one is Checkbox.js and the other is SurveyPage.js where I call the checkbox component. onClick={() => { console.log("label:", label); setChecked(!checked); setAnswer((prevState)=>[...prevState, label]) console.log("answers:", answer) if(answer.includes(label)) { setAnswer(answer.filter(answer => answer !== label)) } else { setAnswer([...answer, label]) } }} https://pastebin.com/aXqBZ3Ki - SurveyPage.js https://pastebin.com/Vq9PkbPs - SurveyCheckbox.js https://postimg.cc/gallery/JGDwv9v - screenshots from the app