Working with React Context and Hooks I am creating a provider called AuthProvider and from the useAuth Hook I call that context to work with it. I have a component called Login in which I call my Hook to access the AuthProvider as follows:
JavaScript
x
10
10
1
import useAuth from '../hooks/useAuth'
2
3
const Login = () => {
4
5
const { hello } = useAuth()
6
7
console.log(hello);
8
9
10
In AuthContext I have the variable “hello” that I pass to the children of my context.
AuthProvider:
JavaScript
1
19
19
1
const AuthContext = createContext()
2
3
const AuthProvider = ({children}) => {
4
5
const hello= 'hello'
6
7
return (
8
<AuthContext.Provider value={{ hello }}>
9
{children}
10
</AuthContext.Provider>
11
)
12
}
13
14
export {
15
AuthProvider
16
}
17
18
export default AuthContext
19
UseAuth Hook:
JavaScript
1
11
11
1
import { useContext } from "react";
2
import AuthContext from "../context/AuthProvider";
3
4
const useAuth = () => {
5
6
return useContext(AuthContext)
7
8
}
9
10
export default useAuth
11
And this is the error:
JavaScript
1
2
1
Uncaught TypeError: Cannot read properties of undefined (reading 'hello')
2
Advertisement
Answer
The problem is that the component you use context but was not wrapped under a context provider
To fix, wrap the component or the root component that has the component as a children under a context provider
JavaScript
1
4
1
<AuthProvider>
2
<Login />
3
</AuthProvider>
4