1

When my checkbox gets checked or unchecked specific data needs to be set. Right now I am setting the value of checked as true or false in a state variable. The problem is it does not have a callback function like setState does so when I update it in the onChange function it does not update in time for the next set of data to get updated properly. Setting the properties on newEnhanceableData depends on if the checkbox is checked or unchecked. How do I update my checked property in time for the next line of newEnhanceableData to have it's properties updated?

Here are the state variables:

const [checkbox, setCheckbox] = useState({checked: true});
const [enhanceableData, setEnhanceableData] = useState({
  name: 'Item Clicked',
  properties: {
    ...defaultProps,
    activityLocation: 'Member - RAQ Contact Details',
    autopopulated: true,
    changeType: 'Add'
  }
});

And here are is where I update them:

<input 
  id='raq-sms-text-checkbox' 
  type='checkbox' 
  defaultChecked={true}
  style={{marginRight: 5}}
  onChange={() => {
    setCheckbox({checked: !checkbox.checked});

    const newEnhanceableData = enhanceableData;
    newEnhanceableData.properties.changeType = checkbox.checked ? 'Add' : 'Remove';
    newEnhanceableData.properties.autopopulated = false;
    setEnhanceableData(newEnhanceableData)

    console.log('checkbox: ', checkbox)
    console.log('enhanceableData: ', enhanceableData)

    sendEnhancedTrackEvent(enhanceableData);
  }} /> 

As you can see here the checked property gets updated after enhanceableData is already set:

enter image description here

1 Answer 1

1

You may not need hooks at all and simply check the checked state inside your onChange function:

<label>
  <input
    type="checkbox"
    onChange={ev => {
      const { checked } = ev.currentTarget;
      console.log(checked) // toggles to true and false
      // continue with the rest
    }}
  />
  Click me
</label>

If you'd like to move the logic somewhere else, useEffect might be useful:

const [checked, setChecked] = useState(true);

useEffect(() => {
   // do-enhanced-computing-stuff-here
}, [checkbox]) // <-- effect only runs if checkbox boolean state changes 

<input checked={checked} onChange={ev => setChecked(ev.currentTarget.checked)} />
Sign up to request clarification or add additional context in comments.

1 Comment

The simple things :)

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.