Search code examples
javascriptreactjslocal-storagereact-toastify

Save multiple objects on Local Storage? Javascript


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


Solution

  • 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