I'm trying to update data from the local host. I have 2 interfaces "loggedInUsers" and "user", one with a default value and the other with an individual value. In this case it is the colour. what am I doing wrong here? I would like to change the current "white" color to "blue".
useEffect(() => {
const usersIdColor = loggedInUsers.map((e) => user?.find((u) => u.id === e.id && u.color !== e.color));
if (usersIdColor) {
localStorage.setItem(
'logged_in_users',
JSON.stringify([...loggedInUsers, { id: user.id, username: user.username, tenantId: user.tenantId, color: 'blue' }])
);
}
}, []);
In order to prevent adding new entries you should filter over the logged in users entry and use that value in replacement.
useEffect(() => {
const WHITE = 'white';
const RED = 'red';
const loggedInUserFiltered = loggedInUsers.filter(({color, ...loggedInUser}) => color === WHITE ? {...loggedInUser, color: RED} : {...loggedInUser, color});
if (usersIdColor) {
localStorage.setItem(
'logged_in_users',
JSON.stringify(loggedInUsers)
);
}
}, []);
You should also add your logic to retrieve only the wanted user using find and so on, like you did, or you can even add conditions to the filter method, that way you could do it all in a single statement.
Something like:
const FIRST_USER = 1;
const loggedInUserFiltered = loggedInUsers.filter(({color, id, ...loggedInUser}) => color === WHITE && id === FIRST_USER ? {...loggedInUser, color: RED, id} : {...loggedInUser, color, id});
BTW: it's local storage.
With this code you are always going to add a new user to the logged_in_users array with the color blue. If you want to update the logged_in_users you need to update the value in the array. Something like this (Not sure how exactly you are matching the user:
useEffect(() => {
const userIndex = loggedInUsers.findIndex((e) => user?.find((u) => u.id === e.id && u.color !== e.color));
if (userIndex) {
loggedInUsers[userIndex]={ id: user.id, username: user.username, tenantId: user.tenantId, color: 'blue' };
localStorage.setItem(
'logged_in_users',
JSON.stringify(loggedInUsers)
);
}
}, []);