Home > Mobile >  local storage problem when trying to fetch data from localstorage using useEffect() in ReactJS
local storage problem when trying to fetch data from localstorage using useEffect() in ReactJS

Time:04-13

I am trying to fetch data in localstorage using ReactJS. Can some one please help me here is my sample code.


let [rows,setRows] = useState([]);

    React.useEffect(() => {
        rows = localStorage.getItem("my_tier_list");
        if(rows){
            setRows(JSON.parse(rows));
        }
  
      },[]);
  
      React.useEffect(() => {
        localStorage.setItem("my_tier_list", JSON.stringify(cart));
      });

Can some one please help me and thanks in advance

CodePudding user response:

Please look into following sandbox: https://codesandbox.io/s/heuristic-rain-n97hf3

  • Set local storage item on some event handler: localStorage.setItem("value", value);
  • Get local storage item with: const localStorageValue = localStorage.getItem("value");

CodePudding user response:

There are three problems to your above code.

  1. You can't directly assign values to your state variable using =, you must do it using the setter functions.
  2. You have not added the dependency list in the second useEffect.
  3. You have not used the correct name to set the localStorage.
let [rows,setRows] = useState([]);

    React.useEffect(() => {
        // you can't directly set a state variable. Create a new local variable
        const localRows = localStorage.getItem("my_tier_list");
        if(localRows){
            setRows(JSON.parse(localRows));
        }
  
      },[]);
  
      React.useEffect(() => {
        localStorage.setItem("my_tier_list", JSON.stringify(rows)); // corrected it to rows
      }, [rows]); // added the array as dependency list. This will trigger this only when "rows" gets changed
  • Related