Home > Software engineering >  TypeError: Cannot read property 'Provider' of undefined React Native Context
TypeError: Cannot read property 'Provider' of undefined React Native Context

Time:04-16

I'm getting error TypeError: Cannot read property 'Provider' of undefined in App.js. In the line <AuthContext.Provider value={{ authorized, setAuthorized }}>.

App.js
....
import React, { useState } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import MyDrawer from './components/Drawer';
import AuthStack from './components/AuthStack';
import AuthContext from './components/authContext.js';

export default function App() {
  const [authorized, setAuthorized] = useState(false)

  return authorized ? (
    <NavigationContainer>
      <MyDrawer />
    </NavigationContainer>
  ) : (
    <AuthContext.Provider value={{ authorized, setAuthorized }}>
      <NavigationContainer>
        <AuthStack />
      </NavigationContainer>
    </AuthContext.Provider>
  );
}

Here is my context:

authContext.js
....
import React from "react";

export const AuthContext = React.createContext({
    authorized: false,
    setAuthorized: () => {},
});

Any ideas in the problem?

CodePudding user response:

Seems that you just need to import with {}:

import { AuthContext } from './components/authContext.js';

Since you didn't export default your AuthContext. More info here

  • Related