Home > Blockchain >  issue with checkboxgroup on change handler
issue with checkboxgroup on change handler

Time:12-23

I am using checkboxgroup from Chakra UI (https://chakra-ui.com/docs/hooks/use-checkbox-group). Basically there is a dropdown with multiple checkboxes and one or more can be selected at the same time. All I want to do is to know the values which are selected and then send this data somewhere else when any of the checkboxes is checked and the library seems to offer very easy way to achieve this by using useCheckBoxGroup hook. However, I am running into a problem. I don't know if I am not doing something right, or this is the actual desired behavior.

    const { value, getCheckboxProps} = useCheckboxGroup({
        onChange: () => {
            const checkBoxState = value as string[]
            console.log(checkBoxState)
            setSearchParams({ 'category': checkBoxState });
        },
    });
    console.log(value)

The hook lets you define onchange event that will fire every time any of checkboxes changes state. However, the problem is that in the onchange itself, the value is still the previous value i.e. before the click on some of the checkboxes. Meaning the console log below shows correct state of checkboxes and the console log inside the onChange shows the previous value (before the click). This kind of makes the hook useless because I want to do something with the CURRENT state inside the onChange event. Please does anyone know if I am doing something wrong or this is not supposed to work how I want it to.

CodePudding user response:

The onChange-event provides a parameter with the current value(s) in, which you can then use to set the search parameters, like this:

const { value, getCheckboxProps} = useCheckboxGroup({
    onChange: (selectedValues: (string | number)[]) => {
        const checkBoxState = selectedValues;
        console.log(checkBoxState);
        setSearchParams({ 'category': checkBoxState });
    },
});

I hope this helps!

  • Related