My issue is that I have an initial object with data in the function. The function receives params with values that are into this initial object. I need to update the initial object every time with the data, which comes from params.
The code:
export function saveLocalStorage(params = {}) {
let state = {
firstName: '',
lastName: '',
role: '',
idToken: '',
auth: false,
id: '',
email: '',
phone: '',
organizationId: '',
lastVisit: '',
}
localStorage.setItem('donisi-new', JSON.stringify(state))
}
params have the same names as names in initial object, example:
saveLocalStorage({
firstName,
lastName,
role,
organizationId,
auth: true,
idToken,
lastVisit: moment(new Date()),
})
So, for example, the first time I received the first object with params, for example:
saveLocalStorage({
firstName: 'La La',
lastName: 'Bla Bla'
})
and second time I received object with params:
saveLocalStorage({
role: 'admin',
phone: '+111111111'
})
How to update the initial state and don't delete the values and only update them?
Thanks to everybody.
This is a function I use to merge 2 JavaScript objects:
function mergeObjects(obj, src) {
for (var key in src) {
if (src.hasOwnProperty(key)) obj[key] = src[key];
}
return obj;
}
So if you had these 2 objects:
var obj1 = {name: 'Bob', age: 30};
var obj2 = {name: 'Steve'};
And ran the function:
mergeObjects(obj1, obj2);
It would return:
{name: 'Steve', age: 30}
To achieve this behaviour you can use the ES6's spread operator (...) to merge objects. It will merge the two object. The new fields will be added from both object and existing ones will be updated.
Just replace your
localStorage.setItem('donisi-new', JSON.stringify(state))
with
localStorage.setItem('donisi-new', JSON.stringify({...state, ...params}))
The order of state and params is important here. This orders means state object will be updated with new values which exist in params object.
Part of the problem with updating initial state is you have state defined in the function, so those values can't be updated. One way to address this is to pull state out into its own file and then reference it in your function.
// state.js
export default {
firstName: '',
lastName: '',
role: '',
idToken: '',
auth: false,
id: '',
email: '',
phone: '',
organizationId: '',
lastVisit: '',
};
Then in your function you can reference and update it as necessary. The next time you call saveLocalStorage, the state will have been updated from the previous call.
import * as state from "./state.js";
export function saveLocalStorage(params = {}) {
/* Update state with values from params example
for (const [key, value] of Object.entries(params)) {
state[key] = value;
}
*/
localStorage.setItem('donisi-new', JSON.stringify(state))
}
I leave part of this in a comment because you may have something else in mind for updating state or before merging.