reactjsnext.jsreact-context

Using context Api with useReducer hook in next.js gives undifined back when useContext is called


I was using context API with useReducer hook in my next.js app, which returns "undefined" when useContext is called with the contextProvider.

This is my code - contextPage:

import React, { createContext, useReducer, useContext } from 'react';
import * as types from '../constants/userConstants';

// initialized global store

export const quizContext = createContext();

// reducer

const reducer = (state, action) => {
  switch (action.type) {
    case types.USER_LOGIN_SUCCESS:
      return // user

    case types.USER_LOGOUT_SUCCESS:
      return // clear user

    default:
      return state;
  }
};

const QuizContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, {
    user: null,
  });

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

export const useQuizContext = () => useContext(QuizContextProvider);

export default QuizContextProvider;

After that, I'm wrapping my provider in _app.js.

And on my Login page, I can not access that.

Login page:

const index = () => {
  const data = useQuizContext();
  console.log(data);
  return <div></div>;
};

Here, data is undefined. Badly stuck.


Solution

  • It should be

    export const useQuizContext = () => useContext(quizContext)