Storing clicked checkboxes (labels) in an array. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

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

11th Jan 2022, 4:01 PM
Filip
Filip - avatar
2 Answers
+ 3
As i understand when you click on first check, you dont see it in console.log,but if you click more than 1 you see old answers? I set this console.log at beggining of your SurvayPage and answers state is updated when i click on checkbox, so it look like it work fine? Test my code, i deleted styles and some missing components. https://codepen.io/PanicS/pen/gOXYpmq If this console.log work just fine answer is time when you access data, in moment you try to access inside survayCheck data is old, you can see updated in next render of survayCheck, if i am not wrong.
24th Jan 2022, 12:30 AM
PanicS
PanicS - avatar
+ 2
Thank you very much, you're right for console.log, it was creating a issue with storing checked labels in an array so I moved it to the parent component in UseEffect and now logic in child is like this: <Field style={styles.defaultCheck} type="checkbox" name={name} value={label} onClick={() => { // console.log("label:", label); setChecked(!checked); if(!checked) { setAnswer([...answer, label]) } else { setAnswer(answer.filter(elem => elem !== label)) } }} /> and now works normally, solved ;) Whether you use some social thing, LinkedIn or something like that to connect? And thank you anyway :D
24th Jan 2022, 12:53 AM
Filip
Filip - avatar