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>
  );
}
1
  • Can you set a default state. Commented Nov 21, 2019 at 14:54

2 Answers 2

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]) 
Sign up to request clarification or add additional context in comments.

1 Comment

You said I cannot rely on function like above, how would you change it, so it becomes reliable? Thank you
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.