score:2

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
    //...
}

Related Query

More Query from same tag