Encountering an issue with login authentication in React Native Django: Unidentified error - Unable to access the property 'isLoggedIn'

I am currently working on integrating a Django authentication system into my React Native app.

Within my app.js file, I have imported the authentication context, which means that the initial value of isLoggedIn upon app launch is set to false. The variable isLoggedIn is used in app.js to determine whether to render the login screen when it is false or load AppNavigator to navigate the user into the app when it is true.

Although I have not yet developed the Django backend, I have temporarily set isLoggedIn to true when the login button is pressed without communicating with Django (this will be resolved once I address this issue).

The issue arises at line 15 of App.js:

const { isLoggedIn } = globalContext;

I have carefully reviewed all relevant import statements and am confident that I am exporting and importing correctly. I have also double-checked the import paths.

Additionally, I have confirmed that isLoggedin and setIsLoggedIn are included in the globalContext variable within AuthContext.js. It is passed into the Context.Provider in AuthContext.js and App.js encapsulates the entire app within Provider, making the auth context accessible throughout the app.

Upon initial loading, the app should display the login screen. Users should be able to input text in the two text fields and press the login button to access the app. However, Expo Go presents an error "TypeError: Cannot read property 'isLoggedIn' of undefined" before displaying the login screen.

Hence, I suspect the root of the problem lies within the two source files provided below. This is why I have omitted the login screen code, as the Login code is not executed due to the program halting beforehand.

App.js

import React, { useEffect, useContext } from "react";
import {
    AppRegistry,
    View,
} from "react-native";
import SplashScreen from "react-native-splash-screen";
import { NavigationContainer } from "@react-navigation/native";

import AppNavigator from "./Navigation/AppNavigator";
import { Context, Provider } from "./Auth/AuthContext";
import Login from "./Screens/LoginScreen";

export default function App() {
    const globalContext = useContext(Context);
    const { isLoggedIn } = globalContext;
    useEffect(() => {
        SplashScreen.hide();
    }, []);

    return (
        <Provider>
            <View style={{ flex: 1 }}>
                <NavigationContainer>
                    {isLoggedIn ? <AppNavigator /> : <Login />}
                </NavigationContainer>
            </View>
        </Provider>
    );
}

AppRegistry.registerComponent("Provisioner", () => App);

AuthContext.js

import React, { useState, useEffect, createContext } from "react";


const Context = createContext();

const Provider = ({ children }) => {

    const [domain, setDomain] = useState("http://*********.uksouth.cloudapp.azure.com:8000");
    const [isLoggedIn, setIsLoggedIn] = useState(false);
    const [appSettings, setAppSettings] = useState({});

    function initAppSettings() {
        fetch(`${domain}/api/v1.0/app/settings`, {
            method: "GET",
        })
            .then(res => {
                if (res.ok) {
                    return res.json();
                } else {
                    throw res.json();
                }
            })
            .then(json => {
                setAppSettings(json);
            })
            .catch(error => {
                console.log("Bad JSON");
                console.log(error);
            });
    }

    useEffect(() => {
        initAppSettings();
    }, []);

    const globalContext = {
        domain,
        isLoggedIn,
        setIsLoggedIn,
        appSettings,
        setAppSettings
    };

    return <Context.Provider value={globalContext}>{children}</Context.Provider>;

};

export { Context, Provider };

Answer №1

Make sure not to call useContext outside the provider's scope.
To fix this issue, elevate the provider above the component tree.

const MainApp = ()=> {
   const appContext = useContext(Context);
   const { userStatus } = appContext; 
   ... add your code here ...
   return someComponent
}

const EnhancedMainApp =‍ ()=> <Provider><MainApp/></Provider>

AppRegistry.registerComponent("Provisioning", () => EnhancedMainApp);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to modify Django modelform without adding new data?

I'm encountering an issue with my Django code where it keeps inserting new rows instead of updating the existing ones. While many others have sought help for a similar problem here, one common solution they often overlook is setting instance, as in fo ...

Separating unique values in an array of objects and storing the rest of the values in a separate

I have an array of JavaScript objects that I need to merge into a single JavaScript object based on their same property value. The remaining values should be grouped into another array named info. Original array: const array = [ { price: 27, ...

Struggling with getting React to successfully fetch data from an Express API. Any suggestions on how

I am having trouble with my fetch call to the express API. Even though I receive a response status of 200, I am still getting the index.html instead of the JSON data I need. Here is an overview of my setup: package.json "version": "1.0.0&qu ...

Tips for verifying password in Django Rest Framework's serializer

I need to verify password and repeated_password sent from the front-end. {"user_data":{"user_name":"jim", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4cecdc9e4c3cbcbc3c8 ...

Is there a way to initiate an Ajax Request when one of the two buttons in a form is clicked?

Is there a way to streamline the code for sending a request from one page to another using a form with 2 buttons? <form method="post"> <button id="button_1" value="val_1" name="but1">button 1</button> <button id="button_2" val ...

When the "change" event listener is added to an input element, the innerHTML is updated as the value increases but not when it decreases

My div block contains a value that I need to adjust as the input value changes. While the adjustment works when the input value increases, it does not change when the input value is decreased. It seems like there may be an oversight in my logic that I am m ...

Creating a general function to accommodate two alike types

Is there a way to modify the addSuffix function to handle two different types and return them simultaneously? Here's an example: type First = { name: string, address: string, } type Second = { name: string ...

"Ionic application encountering issue with retrieving data from email inbox, resulting in undefined

I encountered an issue with creating a user account using Ionic Framework and Firebase. Oddly, the email box returns 'undefined' while the password box functions correctly despite being coded in a similar manner. Below is my HTML snippet: <io ...

Customizing Date Format for Multiple Datepickers on a Single Page using Angular Material (md-datepicker)

I am currently working with angular material and using md-datepicker. My goal is to be able to set different date formats depending on the user's selection. For example, if the user chooses 'daily', I want the datepicker to display 'MM/ ...

Having difficulty removing an item from an array in JavaScript

I've been struggling to remove an object with a specific value from an array, despite trying various codes and syntax examples from this platform. // ISSUE WITH DELETING "CAMPUS DIRECTOR" CODE router.delete("/:id/director", userAut ...

Issue encountered while using Axios to send an http request to a server

I am facing an issue when making a GET request to the jasonplaceholder server to fetch data. Sometimes, the request returns undefined for a brief period before fetching all the data. How can I prevent this undefined response and halt the code execution u ...

Exploring various substances when combining shapes in Three.js enhances the visual appeal and complexity of

I have a vision to construct a Pine tree using 2 different meshes - one for the trunk and another for the bush. Here is what I have tried so far: var pine_geometry = new THREE.Geometry(); var pine_texture_1 = THREE.ImageUtils.loadTexture('./res/text ...

Effortless Like/Unlike feature with a text button option enhanced with ajax functionality and

Struggling to create a simple Like/Unlike button in PHP without refreshing the page. Despite an abundance of tutorials on AJAX and jQuery, implementation remains elusive due to lack of experience. Uncertain where each part of the code goes within which fil ...

Difficulty adjusting the prefix of a formset within Django

My question is regarding a formset and an empty_form in the same HTML document. I am trying to perform calculations with them, but I have encountered an issue. While I was able to extract the ID and perform operations on the empty_form, I am struggling to ...

Difficulty encountered when positioning a container using BootStrap 4

As a newcomer to the world of web development, I encountered an issue while trying to align a container on my webpage. Despite my efforts to center the container using (line 30), the page seems to update but there is no visible change. Can anyone help me ...

Implementing a NestJs application on a microcomputer like a Raspberry Pi or equivalent device

I'm facing a challenge in trying to find a solution for what seems like a simple task. I am aware that using the Nest CLI, I can utilize the command "nest build" to generate a dist folder containing the production files of my project. However, when I ...

Interacting with specific elements by their class using pure javascript

Here is an example of HTML code, in which I am attempting to click a close button. There are multiple close buttons present, but my goal is to click the one inside the mytop class. <div class="mytop"> <a class="mychild" role="button" href="#"> ...

Include ?q=search-term in Django URL

I am working on integrating elastic search with Django and I need to create a parameter in the URL. http://127.0.0.1:8000/search?q=search+term This is the code in urls.py for the view: urlpatterns = [ path('?q=', SearchIndexView.as_view(), ...

Tips for monitoring steps within a straight-forward workflow

In the workflow model, I have a Task with a field that allows users to add approvers for each step in the task. class Task(models.Model): approvers = models.ManyToManyField( get_user_model(), through='TaskStep' ) To keep ...

Creating input fields in a plugin that dynamically initializes multiple fields

I have multiple forms on a single page, each containing a phone number field driven by a JavaScript plugin. As a result, I am faced with having to properly initialize a large number of these fields. Manually initializing them would require: number of for ...