2

how can I work around local Storage is not defined error in next.js. I am quite new to next.js and react. I know that we require to do some form of mounting before checking for local storage data but I cant figure out a way to do it. I am trying to save into local storage so the data doesn't disappear when the page is refreshed

export const GlobalContext = React.createContext();

export const GlobalProvider = (props) => {

const initialState = {
    watchlist: localStorage.getItem("watchlist")
        ? JSON.parse(localStorage.getItem("watchlist"))
        : [],
};



const [state, dispatch] = React.useReducer(AppReducer, initialState);

React.useEffect(() => {
    localStorage.setItem("watchlist", JSON.stringify(state.watchlist));

}, [state])


const addtoWatch = coin => {
    dispatch({ type: "ADD_COIN_TO_WATCHLIST", payload: coin })
}


return (
    <GlobalContext.Provider
        value={{
            watchlist: state.watchlist,
            addtoWatch,
        }}
    >
        {props.children}
    </GlobalContext.Provider>
);

};

TheG
  • 21
  • 1
  • 1
  • 3

4 Answers4

3

localStorage or window.localStorage or global.localStorage

if(typeof window !== "undefined") {
    if(localStorage.getItem("watchlist")) {
      return JSON.parse(localStorage.getItem("watchlist"))
    } else{
    return []
    }
 }
0

You can have a simple if condition for checking window existence: typeof window !== "undefined")

Dvir Hazout
  • 251
  • 1
  • 3
0

I faced the same issues with SvelteKit.

I think this code would works for you and make it your code simpler

create a function for checking window first

  const checkWindow = (action => {
        return typeof window !== undefined ? action : null;
    };

then,

const initialState = {
    watchlist: checkWindow(localStorage.getItem("watchlist"))
        ? JSON.parse(checkWindow(localStorage.getItem("watchlist")))
        : [],
};
0

I have created a function getLocalStorageItem and called this in useEffect with the required key name. After getting the value from localStorage, saved it in a state(i.e currentUser) and used it in initialState.

 const [currentUser, setCurrentUser] = useState({});

  const getLocalStorageItem = (key) => {
    return typeof window !== undefined
      ? window.localStorage.getItem(key)
      : null;
  };

  useEffect(() => {
    setCurrentUser({
      token: getLocalStorageItem("token"),
      refreshToken: getLocalStorageItem("refreshToken"),
    });
  }, []);

  const initialState = {
    auth: {
      isLoggedIn: true,
      currentUser: currentUser,
    },
  };
Azad Ansari
  • 138
  • 1
  • 10