Search code examples
reactjsuse-state

useState change only one value in array


Have an array of pairs, and am using separate filter functions to change the array value. But I'm struggling to only change a single value while retaining the existing ones.

const [filters, setFilters] = useState({
        fur: '',
        expression: ''
    })

const filterFur = (fur) => e => {
        setFilters({
            fur: fur
        })
    }

    const filterExpression = (expression) => e => {
        setFilters({
            expression: expression
        })
    }
    
    ...
    
    <label className="label"> 
       <input type="radio" name="checkbox" value="All Furs" onClick={filters.fur === '' ? null : filterFur('')}/> All
    </label>

When onClick triggers the function, it sets fur to the desired value, but removes expression entirely. How would I keep the expression value, while changing only fur?


Solution

  • Make use of the spread operator to modify the desired parts of state and copy the other parts:

    setFilters({ ...filters, fur: fur });
    setFilters({ ...filters, expression: expression });
    

    Here is some more official documentation:
    https://reactjs.org/docs/optimizing-performance.html#the-power-of-not-mutating-data.
    https://reactjs.org/docs/hooks-reference.html#functional-updates.
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax