-1

I have 2 rooms {roomId: room1, roomId: room2} and I want to save Object for each rooms on localStorage.

The object looks like

let notifiedRoom = {
    roomId: roomId,
    dismissed: true
}; 

The notifiedRoom Object is saved on localStorage when the user closes notification for respective room.


import React from 'react';
import { toast } from 'react-toastify';


const RoomNotification = (props) => {

  const { roomId, message } = props;

  const setLocalStorage = (roomId) => {
    let notifiedRoom = {
        roomId: roomId,
        dismissed: true
       }; 
    localStorage.setItem('notifiedRoom', JSON.stringify(notifiedRoom));
  };

  const notify = () => {
    toast(<div><p>{roomId}</p><p>{message}</p></div>,
        {
            toastId: roomId,
            position: "top-center",
            draggable: true,
            onClose:() => setLocalStorage(roomId)
        });
   };

}

the problem I have is this will only save a object for a room at a time. So if you close room1 Notification then on localStorage there is roomId: room01, dismissed: true, if I close room2 Notification then the previous localStorage object for room1 is overwritten by room2.

I only need it to overwrite if the roomId matches. Else just create new object for every different roomId on locatStorage.

Many thanks

Jereme
  • 427
  • 7
  • 15

3 Answers3

1

Instead of doing this {roomId: room1, roomId: room2} you can simply do this:

{room1: room1Data, room2: room2Data}

So if you want to update any one for example room1.

const setLocalStorage = (roomId) => {
   const initialUpdateData = JSON.parse(localStorage.getItem('notifiedRoom')) ||{room1:null,room2:null}
    let updatedRoom = {
   ...initialUpdateData,
    [updatedRoom]:{
      roomId: roomId,
        dismissed: true
  }
  }; 
    localStorage.setItem('notifiedRoom', JSON.stringify(updatedRoom));
  };

Note: updatedRoom will be your room1 or room2

Shubham Verma
  • 4,918
  • 1
  • 9
  • 22
0

its easy you can just give a name to the new local storage and set the array to it

localStorage.setItem('1', JSON.stringify(new_array));
localStorage.setItem('2', JSON.stringify(new_array));

Like wise - so it will create new storage for each notified room

And again when you need to retrieve the storage - can retrieve by it name

var room1= JSON.parse(localStorage.getItem('1'));
var room2= JSON.parse(localStorage.getItem('2'));

Hope this is what your looking for

0

You need to have unique key inside one object so :

{room1: {dismissed: true}, room2: {dismissed: true}}

const setLocalStorage = (roomId) => {
 const notifiedRoom = JSON.parse(localStorage.getItem('notifiedRoom'))
 notifiedRoom[roomId] = {dismissed: true}
 localStorage.setItem('notifiedRoom', JSON.stringify({...notifiedRoom}));
};