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
//...
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…