0

I have a problem with context, context api return to me undefined value.

Here is my code :

import { createContext } from "react";

const authContext = createContext();

export default authContext;

authContext.js

import React, { useReducer } from "react";
import authContext from "./authContext";
import authReducer from "./authReducer";

const authState = () => {
  const initState = {
    authValidte: false,
    authToken: null,
    authId: null,
  };
  const [state, dispatch] = useReducer(authReducer, initState);
  return (
    <authContext.Provider
      value={{
        authValidte: state.authValidte,
        authToken: state.authToken,
        authId: state.authId,
      }}
    >
      {props.children}
    </authContext.Provider>
  );
};

export default authState;

authState.js

Component who want to use context :

...
import authContext from "./context/auth/authContext";

function App() {
  const AuthContext = useContext(authContext);
  console.log(AuthContext); // undefined
...
3
  • How is app component rendered and how and where is authState rendered Commented May 16, 2020 at 13:00
  • I don't use authState, where should I use it? Commented May 16, 2020 at 13:03
  • I know, authState is a wrapper for index.js component. Commented May 16, 2020 at 13:08

2 Answers 2

1

First, note that custom component should be Uppercased (AuthState, AuthContext.Provider etc.).

For authContext to be available in App it must be a child of AuthContext.Provider. Read about Context in the docs.

<AuthState>
 <App/>
</AuthState>
Sign up to request clarification or add additional context in comments.

Comments

1

In order for your App Component to use context, you need to render the authState provider higher up in the hierarchy of App component

Ideally it should be the common parent of all the components that may need to use it.

Also note that your component names must start with upperCase characters index.js

import AuthState from '/path/to/authState.js'

export default () => (
   <AuthState>
      <App/>
   <AuthState>
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.