Home > Net >  State is always undefined in nextjs useReducer and useContext
State is always undefined in nextjs useReducer and useContext

Time:03-09

I am using context api in my nextjs project but whenever i am trying to get value from state using context api it is always throwing error "undefined"

AppReducer.js

const initialState = {
    isMobile: false,
    user: {},
};

export const AppReducer = (state = initialState, action) => {
    switch (action.type) {
        case "init_stored": {
            return action.value;
        }
        case "setMobile": {
            return {
                ...state,
                isMobile: (typeof window !== "undefined") && window.innerWidth <= 768,
            };
        }
        case "setUser": {
            return {
                ...state,
                user: action.payload,
            };
        }
        default: {
            return state;
        }
    }
};

AppContext.js

import { createContext, useContext, useMemo, useReducer } from "react";
import { AppReducer, initialState } from "./AppReducer";

const AppContext = createContext();

export function AppWrapper({ children }) {
    const { state, dispatch } = useReducer(AppReducer);
    console.log("AppWrapper: state", state);

    const contextValue = useMemo(() => {
        return { state, dispatch };
    }, [state, dispatch]);

    return (
        <AppContext.Provider value={contextValue}>{children}</AppContext.Provider>
    );
}

export function useAppContext() {
    return useContext(AppContext);
}

_app.js

import { AppWrapper } from 'context/AppContext'
import Layout from '@/components/layout'

function MyApp({ Component, pageProps }) {
   return (
      <AppWrapper>
        <Layout>
          <Component {...pageProps} />
        </Layout>
      </AppWrapper>
  )
}

export default MyApp

I am trying to access it inside my homepage like this

 const { state } = useAppContext();
    console.log(state, 'state');

Please help what wrong i am doing or anything i am missing here ?

CodePudding user response:

Finally found). Use [] not {}

const [state, dispatch] = useReducer(AppReducer, { initialState: 'test'});

And call state in Home page

const state = useAppContext()

CodePudding user response:

Please use this way

mport { createContext, useContext, useMemo, useReducer } from "react";
import { AppReducer, initialState } from "./AppReducer";

const AppContext = createContext({});

export function AppWrapper({ children }) {
    const [ state, dispatch ] = useReducer(AppReducer);
    console.log("AppWrapper: state", state);


    return (
        <AppContext.Provider value={{state, dispatch}}>{children}</AppContext.Provider>
    );
}

export function useAppContext() {
    return useContext(AppContext);
}
  • Related