Reputation: 4843
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
...
Upvotes: 0
Views: 1495
Reputation: 281626
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>
)
Upvotes: 1
Reputation: 53874
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>
Upvotes: 1