0

i have this code which works perfectly fine, but when i update something in the local storage my app doesnt get updated unless i reload the app. What i want to do is to automatically update the data in my app as soon as the data in chrome storage changes:

    const [profiles, setProfiles] = useState([]);
     useEffect(()=>{
   
      chrome.storage.local.get(["profiles"], (result) => {
        if (result.profiles) {
            console.log(result.profiles);
         
            setProfiles(  result["profiles"]);
          
        
            console.log(profiles);
        }
    });       
    },[])


  //run every time when the data changes
  useEffect(()=>{
    chrome.storage.local.set({ "profiles": profiles });
    console.log("running");
  },[profiles])
Talha
  • 36
  • 1

2 Answers2

1

I've put together an example how to use chrome.storage in React app. There is a listener that listens to changes (which can be triggered with content and/or background script). Second listener fetches the current data when component mounts.

import React, { useState } from "react";

const App = () => {
  const [storageData, setStorageData] = useState();

  // Effect 1: Attech/remove storage onChanged listener
  useEffect(() => {
    const listener = () => {
      chrome.storage.sync.get(["storageData"], (result) => {
        setStorageData(result.storageData);
      })
    };
    chrome.storage.onChanged.addListener(listener);
    return () => {
      chrome.storage.onChanged.removeListener(listener);
    };
  }, []);

  // Effect 2: Sync local state with storage data on mount
  useEffect(() => {
    // 'sync' can be 'local', depends on your usecase
    chrome.storage.sync.get(["storageData"], (result) => {
      setStorageData(result.storageData);
    })
  }, []);
  
  // Example event handler to update the storage
  const someEventHandler = (event) => {
    chrome.storage.sync.set({ storagedata: event.target.value}, () => {
      alert("storage updated")
    })
  }

  return (
    <div>
      <pre>{JSON.stringify(storageData, null, 2)}</pre>
      {/* ... */}
    </div>
  );
};
HynekS
  • 2,738
  • 1
  • 19
  • 34
-1

You will need to listen to onstorage event from your window, and apply the logic you need there

https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event

window.onstorage = () => {
  // When local storage changes, dump the list to
  // the console.
  console.log(JSON.parse(window.localStorage.getItem('sampleList')));
};

or

window.addEventListener('storage', () => {
  // When local storage changes, dump the list to
  // the console.
  console.log(JSON.parse(window.localStorage.getItem('sampleList')));
});

Please refer to this answer too: https://stackoverflow.com/a/56662261/1540560

Hassen Ch.
  • 1,693
  • 18
  • 31