0

I have a state of array of object, and i want to save checked checkbox ids inside. in form of

[ 
 {
   name: 'Question 1',
   checked: '1,2' // so 1 and 2 was checked
 }
]

but with following code my state is either empty array of objects or contains only one object inside array when i uncheck checkbox.

  const { id, answer } = props.answers;
  const [answers, setAnswers] = useState([{}]);

  function handleChange(e) {
    setAnswers([{ name: e.target.name, checked: e.target.value }]);
    console.log(answers); // empty when i check checkbox, gets filled after unchecking
  }
  return (
    <Answer>
      <label>
        <input
          type="checkbox"
          name={answer}
          value={id}
          defaultChecked={false}
          onChange={handleChange}
        />
        {answer}
      </label>
    </Answer>
  );
}
Curtis
  • 101,612
  • 66
  • 270
  • 352

2 Answers2

2

You cannot rely on a function like:

function handleChange(e) {
    setAnswers([{ name: e.target.name, checked: e.target.value }]);
    console.log(answers); 
  } 

to have access to the new state this is because the setState function is asynchronous so you are trying to console.log a value that may not be set yet. Therefore you need to use a lifecycle method or the useEffect hook with answers as a dependancy (the second argument expects an array so as [answers]).

useEffect runs after first render and after ever render the answers state changes

useEffect(() => {
 console.log(answers) // get my new expected value of answers
}, [answers]) 
rose specs
  • 905
  • 8
  • 18
0

useEffect will be rerun when answers is changed like so:

import react, {useState, useEffect} from 'react';

const [answers, setAnswers] = useState([{}]);

 handleChange = e =>{
    setAnswers([{ name: e.target.name, checked: e.target.value }]);
  }

  useEffect(() => {
     console.log(answers); //get the updated state here
  }, [answers]);

For more go through this

blueseal
  • 2,726
  • 6
  • 26
  • 41