Home > Enterprise >  React 18 useState resets array in functional component
React 18 useState resets array in functional component

Time:10-29

I have a series of checkboxes that need to push their name into a state array when checked, and remove their name when they are unchecked. No matter what I do, checking any sets the array to contain only that checkbox's name.

const [selectedItems, setSelectedItems] = useState([]);

useEffect(()=> {
    // Log selectedItems out every time it changes.
    console.log(selectedItems) // Always only the last selected checkbox name, no others.
}, [selectedItems])

const onCheckChange = e=> {
    console.log(e.target.name, e.target.checked) // Are as expected, the name and value.
    if (e.target.checked) {
        setSelectedItems(prev=> [...prev, e.target.name])
        // setSelectedItems([...selectedItems, e.target.name]) // Same result.
    } else {
        setSelectedItems( prev=> prev.filter(s=> s!==e.target.name) )
        // setSelectedItems(selectedItems.filter(s=> s!==e.target.name)) // Same result.
    }
}

Every time I check a checkbox, selectedItems is set to contain only the selected item's name. Every time I uncheck a checkbox, setSelectedItems is set to [].

This seems like the most normal pattern ever, but there must be some weirdness with arrays and useState? Thanks to anyone who can help!

CodePudding user response:

The problem is in e.target.name. Most likely all your checkboxes are using the same name.

To fix, try to give different names, or use something else to find which checkbox was interacted (for example use index, with adding it as an argument of your onChange handler)

  • Related