AuthContext.js
import React, { createContext, useContext, useState } from "react";
export const AuthContext = createContext();
export const useAuth = () => useContext(AuthContext)
export default function AuthProvider({ children }) {
const [number, setNumber] = useState(0)
setInterval( () => setNumber(number+1), 10000 )
const valueToBeShared = {number}
return (
<AuthContext.Provider value={ valueToBeShared }>
{children}
</AuthContext.Provider>
);
};
FooterComponent.jsx
import { useContext } from "react";
import { AuthContext } from "./AuthContext";
function FooterComponent() {
const authContext = useContext(AuthContext)
console.log(`Footer component - ${authContext.number}`);
return (
<div>
Your Footer
</div>
)
}
export default FooterComponent
TypeError: Cannot read properties of undefined (reading ‘number’)
at FooterComponent (:64:49)
at renderWithHooks (:12163:28)
at mountIndeterminateComponent (:15575:23)
at beginWork (:16592:24)
at beginWork$1 (:20001:24)
at performUnitOfWork (:19458:22)
at workLoopSync (:19392:15)
at renderRootSync (:19370:17)
at recoverFromConcurrentError (:18968:30)
Unable to read number in FooterComponent
1. Added React.createContext();
2. Checked createContext(number);
2
Answers
Check whether you have enclosed the Components in the
App
with theAuthProvider
to make use of the Provider functions and values.First, make sure FooterComponent is under a wrapped element of the provider. Second, as you name your file AuthContext.js you need to import it as it
You can name your file as index.js under an AuthContext folder and then you can import it like this: