skip to Main Content

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


  1. Check whether you have enclosed the Components in the App with the AuthProvider to make use of the Provider functions and values.

    import AuthProvider from "./path to AuthProvider"
    
    function App() {
      return (
        <BrowserRouter>
          <AuthProvider>
              // Your routes or any other components that needs to use the Provider
          </AuthProvider>
        </BrowserRouter>
      );
    }
    
    export default App;
    
    Login or Signup to reply.
  2. 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

    import {} from './AuthContext.js'
    

    You can name your file as index.js under an AuthContext folder and then you can import it like this:

    import {..} from './AuthContext'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search