Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactNative Context returns undefined when trying to access a value

I am trying to use the values/functions from my context but every time I console.log a value that Coes from context the value is undefined.

This is my Context:

import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import React, {createContext, FC, useEffect } from 'react';
import { useState } from 'react';
import {fbInit, setNewUserFireStore, subscribeUserFS } from '../services/FirebaseServices';

const initialState = {
    signedIn: false,
  }

export const FirebaseContext = createContext();

export const FirebaseContextProvider = ({children}) => {
    const [isUserSignedIn, setIsUserSignedIn] = useState(initialState.signedIn);

    useEffect(() => {
        fbInit();
    })

    const testLog = () => {
        console.log("TAG Test Log Func")
    }

    return (
        <FirebaseContext.Provider value={{isUserSignedIn, setIsUserSignedIn}}>
            {children}
        </FirebaseContext.Provider>
    );
}

This is where I am trying to use the values (I am trying to log the values when I press the Button)

import { useNavigation } from '@react-navigation/native';
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import {Button, Card, TextInput} from 'react-native-paper';
import { FirebaseContext } from '../../context/FirebaseContext';
import React, {useContext, useEffect, useState } from 'react';

const initialUserState = {
    userName: 'Nicole Lopez',
    password: '1001008888',
}

export default function LoginScreen() {
    const [disabled, setDisabled] = useState(false);
    const [userState, setUserState] = useState(initialUserState);
    const { fbContext } = useContext(FirebaseContext);
    const navigation = useNavigation();

    const onInputChange = (field, value) => {
        setUserState({
            ...userState,
            [field]: value
        })
    }

    useEffect(() => {
        setDisabled(userState.userName.length === 0 || userState.password.length === 0);
    }, [userState.userName, userState.password])

  return (
    <View style={styles.container}>
            <Card style={styles.card}>

                <TextInput
                    mode="outlined"
                    label="Förnamn & Efternman"
                    defaultValue={userState.userName}
                    onChangeText={text => onInputChange("username", text)}
                    right={<TextInput.Icon name="account" onPress={() => {
                    }}/>}
                    style={styles.textInput}/>

                <TextInput
                    mode="outlined"
                    label="Anställningsnummer 100100xxxx"
                    defaultValue={userState.password}
                    right={<TextInput.Icon name="lock"/>}
                    onChangeText={text => onInputChange("password", text)}
                    style={styles.textInput}/>
            </Card>

            <View style={styles.buttonRow}>

                <Button
                    color={disabled ? "gray" : undefined}
                    disabled={disabled}
                    mode={'contained'}
                    icon={'login'}
                    onPress={() => {
                        console.log("TAG isUserSignedIn: " + fbContext?.isuserSignedIn)
                        //fbContext?.testLog()
                        //console.log("TAG LOGIN BTN PRESSED")
                        //navigation.navigate('HomeScreen')
                    }}>Login</Button>
            </View>
        </View>
  );
}

This is my App.js:

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import {StackScreens} from './src/helpers/types';
import { NavigationContainer, useNavigationContainerRef } from '@react-navigation/native';
import LoginScreen from './src/screens/LoginScreen/LoginScreen';
import HomeScreen from './src/screens/HomeScreen/HomeScreen';
import {doc, getFirestore, onSnapshot, setDoc, Unsubscribe as UnsubscribeFS} from 'firebase/firestore';
import { FirebaseContextProvider, FirebaseContext } from './src/context/FirebaseContext';
import { useContext } from 'react';
//import { navigationRef } from './RootNavigation';

//const userDocument = firestore().collection("users").doc('Cstl3bA9xwwH3UwHZJhA').get();
const Stack = createNativeStackNavigator();

export default function App() {
  return (
    <FirebaseContextProvider>
      <Content />
    </FirebaseContextProvider>
  );
}

export const Content = () => {

  const navigationRef = useNavigationContainerRef();
  const firebaseContext = useContext({FirebaseContext});

  return (
    <NavigationContainer ref={navigationRef}>
        <Stack.Navigator initialRouteName="LoginScreen">
          <Stack.Screen name="LoginScreen" component={LoginScreen} />
          <Stack.Screen name="HomeScreen" component={HomeScreen} /> 
        </Stack.Navigator>
      </NavigationContainer>
  );
}

Don't know what I have missed, I have installed the packages, I have tried to log different values but all seem to be undefined :/

like image 431
Nicole Lopez Avatar asked Mar 31 '26 22:03

Nicole Lopez


1 Answers

I believe it is undefined because you're trying to destructure the context value, maybe

 const { fbContext } = useContext(FirebaseContext);

should be

 const fbContext = useContext(FirebaseContext);
like image 200
Henrique Possatto Avatar answered Apr 03 '26 11:04

Henrique Possatto