Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading