Home > Enterprise >  React Native Component Exception: undefined is not an object (evaluating_useContext.isAuthenticated
React Native Component Exception: undefined is not an object (evaluating_useContext.isAuthenticated

Time:12-02

Im trying to authenticate a user and pull in context from another file. I feel like what Im doing is pretty straight forward but I keep getting the same error. Am I importing useContext wrong?

import React, { useContext } from "react";
import { NavigationContainer } from "@react-navigation/native";

import { AppNavigator } from "./app.navigator";
import { AccountNavigator } from "./account.navigator";

import { AuthenticationContext } from "../../services/authentication/authentication.context";

export const Navigation = () => {
  const { isAuthenticated } = useContext(AuthenticationContext);

  return (
    <NavigationContainer>
      {isAuthenticated ? <AppNavigator /> : <AccountNavigator />}
    </NavigationContainer>
  );
};

The Context per a request from a user below to help provide more information

import React, { useState, createContext } from "react";
import * as firebase from "firebase";

import { loginRequest } from "./authentication.service";

export const AuthenticationContext = createContext();

export const AuthenticationContextProvider = ({ children }) => {
  const [isLoading, setIsLoading] = useState(false);
  const [user, setUser] = useState(null);
  const [error, setError] = useState(null);

  const onLogin = (email, password) => {
    setIsLoading(true);
    loginRequest(email, password)
      .then((u) => {
        setUser(u);
        setIsLoading(false);
      })
      .catch((e) => {
        setIsLoading(false);
        setError(e);
      });
  };

  return (
    <AuthenticationContext.Provider
      value={{
        user,
        isLoading,
        error,
        onLogin,
      }}
    >
      {children}
    </AuthenticationContext.Provider>
  );
};


CodePudding user response:

You're not passing anything in to the createContext call here:

export const AuthenticationContext = createContext();

so useContext(AuthenticationContext) will return undefined. Therefore it will throw this error when you try to destructure and read an isAuthenticated property. It seems you need your context to be an object with an isAuthenticated property.

You might find it helpful to read the basics of React context here, and specifically about useContext here.

  • Related