Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

next.js - How to setup and use local storage in next js

Can somebody help me to solve an issue with Next JS and localstorage. I am building an ecommerce app where when a user puts an item in their basket, I want to be able to save it to the local storage. My current implementation doesn't work and I am geting an error that says 'Cannot read property 'basket' of undefined'. Below is my code snippet.

export const StateProvider = ({ children }) => {
  const initialState = () => {
    if (typeof window !== 'undefined') {
      return {
        basket:
          window.localStorage.getItem('basket') === null
            ? []
            : window.localStorage.getItem('basket'),
        viwedItems: [],
        saved: [],
      };
    }
  };

  const [state, dispatch] = useReducer(productReducer, initialState());
  const [durationNotification, setDurationNotification] = useState(true);
  const [showMiniBasket, setMiniBasket] = useState(false);

  useEffect(() => {
    window.localStorage.setItem('basket', state.basket);
  }, [state.basket]);
question from:https://stackoverflow.com/questions/66062892/how-to-setup-and-use-local-storage-in-next-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue occurs because state is undefined when running on the server, so it'll throw an error when setting the value on the useEffect's dependency array: [state.basket].

There are several ways this could be fixed, but one of them is to return an empty object from initialState if typeof window !== 'undefined' is false.

export const StateProvider = ({ children }) => {
    const initialState = () => {
        if (typeof window !== 'undefined') {
            return {
                basket:
                window.localStorage.getItem('basket') === null
                    ? []
                    : window.localStorage.getItem('basket'),
                viwedItems: [],
                saved: [],
            };
        }
        return {
            basket: [],
            viewedItems: [],
            saved: []
        }; // Add this so `state` is not undefined on the server-side
    };

    const [state, dispatch] = useReducer(productReducer, initialState());

    useEffect(() => {
        window.localStorage.setItem('basket', state.basket);
    }, [state.basket]); // Accessing `state.basket` will no longer throw an error
    //...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...