javascriptreactjsgoogle-chrome-extensionreact-hooksuse-effect

useEffect to to update a state when data in chrome.storage.local changes


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])

Solution

  • 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: Attach/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>
      );
    };