Home > Software design >  React setState not pushing value FIRST TIME ONLY
React setState not pushing value FIRST TIME ONLY

Time:09-23

Noob question on the way... :(

Working with multiple checkbox and setting state is never getting first value event though value is there.

Console

enter image description here

As show above "value" is being printed on selection.

code

function onChange (e: any) {
        const isChecked = e.target.checked
        const value = e.target.value
        console.log('bool', isChecked, value)
        if(isChecked) {
            console.log('inside val', value)
            setChosenSpeciality([...chosenSpeciality, value])

            console.log('added array', chosenSpeciality)
            filterBySpecialty(chosenSpeciality)
        } else {
            setChosenSpeciality(chosenSpeciality.filter(item => item !== value))
            filterBySpecialty(chosenSpeciality)

            console.log('rest from remove', chosenSpeciality)
        }
    }

<CheckboxContainer>
            {
                   specialties.map((specialty, index) => (
                    <label>  
                        <Checkbox  
                            type="checkbox"
                            name={specialty}
                            value={specialty} 
                            key={index}
                            onClick={onChange}
                        />  
                        {specialty}
                    </label>
                   ))
            }
            </CheckboxContainer>

Thanks for any help, have a good one!

CodePudding user response:

Your issue seems like you are expecting the state to updated immediately which is not the case–it is actually an async operation.

This form of setState() is also asynchronous, and multiple calls during the same cycle may be batched together.

Ref

Update to take this into consideration:

function onChange (e: any) {
        const isChecked = e.target.checked
        const value = e.target.value
        console.log('bool', isChecked, value)
        if(isChecked) {
            console.log('inside val', value)
            const temp = [...chosenSpeciality, value];
            setChosenSpeciality(temp)

            console.log('added array', temp)
            filterBySpecialty(temp)
        } else {
            const temp = chosenSpeciality.filter(item => item !== value);
            setChosenSpeciality(temp)
            filterBySpecialty(temp)

            console.log('rest from remove', temp)
        }
    }
  • Related