Search code examples
javascriptreactjslodash

Change object nested property value using lodash in react


I need to change dynamically nested properties of an object by iterating through an array of properties

import {set} from 'lodash';

const [request, setRequest] = useState(someDefaultProps);

const someFun = (properties) => {
    let newRequest = {};

    properties.forEach(({property, value}) => {
        newRequest = set(request, property, value);
    })
    
    setRequest(newRequest);
}

After changing the request through usestate, a new request should be executed, but nothing happens, since usestate does not fire.

I also tried to use the set function from lodash/fp and although now the request works, the application behaves very strange. In this case, the request data is old even after some changes. For example, there is a radio button, when you click on it, the someFlag field from the request object should be set to false, which is what happens. But if you start typing in the input field, another property of the request object changes, and the old value from someDefaultProps is set in the someFlag field, although someFlag should not change during input.

I would be grateful for your help


Solution

  • Most of lodash library functionality already in modern versions of JS

    Sometimes it is worth to learn new stuff and not to fight with libraries integration.

    const [request, setRequest] = useState(someDefaultProps);
    
    const someFun = (properties) => {
        const newRequest = {...request}; // make sure to create new instance and not use the original state
        properties.forEach(({property, value}) => {
            newRequest[property] = value
        })
        setRequest(newRequest);
    }