Encountering the error "TypeError: null is not an object (evaluating '_ref.user')" with onAuthStateChanged in React Native using Firebase and useContext

I'm encountering an error in my useCachedResources.ts file and I'm uncertain of the cause. These three files are what I'm currently working with. I have a suspicion that the issue lies in the initial null value, but I am conditionally rendering my Auth and App navigation stacks. Perhaps I should include the firebase onAuthStateChanged inside the useCachedResources template?

AuthenticatedUserProvider.tsx

import { useState, createContext } from 'react';

export interface IUser {
  uuid: string;
  email: string | null;
}

export type AuthContextType = {
  user: IUser;
  setUser: (newUser: IUser | null) => void;
};

export const AuthenticatedUserContext = createContext<AuthContextType | null>(null);

export const AuthenticatedUserProvider = ({ children }: { children: React.ReactNode }) => {
  const [user, setUser] = useState<IUser | null>(null);

  return (
    <AuthenticatedUserContext.Provider value={user ? { user, setUser } : null}>
      {children}
    </AuthenticatedUserContext.Provider>
  );
};

navigation.ts

export default function Navigation({ colorScheme }: { colorScheme: ColorSchemeName }) {
  const { user } = useContext(AuthenticatedUserContext) as AuthContextType;

  return (
    <NavigationContainer linking={LinkingConfiguration} theme={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
      {user ? <AppStack /> : <AuthStack />}
    </NavigationContainer>
  );
}

useCachedResources.ts

export default function useCachedResources() {
  const { user, setUser } = useContext(AuthenticatedUserContext) as AuthContextType;
  const [isLoadingComplete, setLoadingComplete] = useState(false);

  useEffect(() => {
    async function loadResourcesAndDataAsync() {
      try {
        SplashScreen.preventAutoHideAsync();

        await Font.loadAsync({
          ...FontAwesome.font,
          'poppins-400': require('../assets/fonts/poppins-400.ttf'),
          'poppins-700': require('../assets/fonts/poppins-700.ttf'),
          'poppins-900': require('../assets/fonts/poppins-900.ttf'),
        });

        const unsubscribeAuthStateChanged = onAuthStateChanged(auth, (authenticatedUser) => {
          authenticatedUser ? setUser({ uuid: authenticatedUser.uid, email: authenticatedUser.email }) : setUser(null);
        });

        return unsubscribeAuthStateChanged;
      } catch (e) {
        console.warn(e);
      } finally {
        setLoadingComplete(true);
        SplashScreen.hideAsync();
      }
    }

    loadResourcesAndDataAsync();
  }, [user]);

  return isLoadingComplete;
}

https://i.sstatic.net/hlWzt.png

Answer №1

When initializing your context with null, destructuring cannot be used. For instance, the code below...

const { user } = null;

will result in the following error in the browser:

Uncaught TypeError: Cannot destructure property 'user' of 'null' as it is null.

My suggestion is to start your context with a placeholder value. This approach will also eliminate the need for adding as AuthContextType repeatedly.

export type AuthContextType = {
  user: IUser | null; // making user optional rather than mandatory in the context
  setUser: (newUser: IUser | null) => void;
};

// initializing with a placeholder / no-op context
export const AuthenticatedUserContext = createContext<AuthContextType>({
  user: null,
  setUser: () => {}
});

export const AuthenticatedUserProvider: React.FC = ({ children }) => {
  const [user, setUser] = useState<IUser | null>(null);

  return (
    <AuthenticatedUserContext.Provider value={{ user, setUser }}>
      {children}
    </AuthenticatedUserContext.Provider>
  );
};

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

Issue: The inject() function must be activated within an injection context, however, the origin cannot be located

While utilizing angularfire's authentication service for user registration and login in my application, I encountered an error when triggering the register or sign-in method: Error: inject() must be called from an injection context Despite attempting ...

activeStyle is not a valid property for type 'IntrinsicAttributes'

I encountered an issue while attempting to utilize NavLink in a react typescript project. The error message states: "Property 'activeStyle' does not exist on type 'IntrinsicAttributes & NavLinkProps & RefAttributes'." import Rea ...

Is it feasible to incorporate a method into a prototype and ensure that 'this' is associated with the appropriate type in TypeScript?

I have a scenario where I need to add a new method to a prototype, specifically to a class created using TypeScript. Here is an example: declare module "./MyClass" { interface MyClass { myNewMethod(); } } MyClass.prototype.myNewM ...

Troubleshooting: JavaScript code not functioning properly with variable input instead of fixed value

I have encountered an issue with a JS function that I'm using. The function is shown below: // A simple array where we keep track of things that are filed. filed = []; function fileIt(thing) { // Dynamically call the file method of whatever ' ...

Simplifying parameter types for error handling in app.use callback with Express.js and TypeScript

With some familiarity with TypeScript but a newcomer to Express.js, I aim to develop a generic error handler for my Express.js app built in TypeScript. The code snippet below is functional in JavaScript: // catch 404 and forward to error handler app.use((r ...

Guide on updating a single element in a Firebase array

I have an array stored in my firebase database, structured like this: matches:[ {match:{id:1,data:...}}] I am looking for a way to update just one specific item within this array. Let's say I want to locate the match with the ID of 32 and modify its ...

acquire tabulations from every single document within the templates on DocuSign

When using Docusign, it is possible to retrieve tabs data for a specific document within a template by specifying the documentId. However, I have not been able to locate a method to obtain tabs data for all documents contained within a template. ...

The absence of class properties transformation in React-pdf is causing an issue

Currently, I am attempting to showcase a PDF file on a website using React. The issue I am encountering arises after installing react-pdf and including import { DOCUMENT } from 'react-pdf'. The project fails to compile, displaying the subsequent ...

What could be causing the Angular router outlet to not route properly?

Check out this demo showcasing 2 outlets (Defined in app.module.ts): <router-outlet></router-outlet> <router-outlet name="b"></router-outlet> The specified routes are: const routes: Routes = [ { path: 'a', com ...

Retrieving an item from AsyncStorage produces a Promise

Insight I am attempting to utilize AsyncStorage to store a Token after a successful login. The token is obtained from the backend as a response once the user clicks on the Login button. Upon navigating to the ProfileScreen, I encounter difficulties in ret ...

creating a JSON array within a function

I am currently developing an Angular application and working on a component with the following method: createPath(node, currentPath = []){ if(node.parent !==null) { return createPath(node.parent, [node.data.name, ...currentPath]) } else { retu ...

Tips for properly importing types from external dependencies in TypeScript

I am facing an issue with handling types in my project. The structure is such that I have packageA -> packageB-v1 -> packageC-v1, and I need to utilize a type declared in packageC-v1 within packageA. All the packages are custom-made TypeScript packa ...

Error Message: The Query<DocumentData> type cannot be assigned to the DocumentReference<DocumentData> parameter

Currently, I am attempting to execute a query against Firestore data. Here is my code snippet: import { collection, getDoc, query, where } from "firebase/firestore"; import { db } from "../../utils/firebaseConfig"; const getQuery = a ...

Angular Material 2 with Customized Moment.js Formatting

Is there a way to display the year, month, day, hours, minutes, and seconds in the input field of my material datepicker? I have successfully customized the parse() and format() methods in my own DateAdapter using native JavaScript objects. Howe ...

Tips for resolving the warning message: "Utilize a callback function in the setState method to reference the

I'm having an issue with this code fragment as ESLint is giving me a warning: "Use callback in setState when referencing the previous state react/no-access-state-in-setstate". Can someone help me resolve this? const updatedSketch = await ImageManipula ...

What is the process for deploying a Lambda function using Terraform that has been generated with CDKTF

Currently, I am following a tutorial by hashicorp found at this link. The guide suggests using s3 for lambda deployment packages. // in the process of creating Lambda executable const asset = new TerraformAsset(this, "lambda-asset", { ...

Problem with moving functions from one file to another file via export and import

I currently have the following file structure: ---utilities -----index.ts -----tools.ts allfunctions.ts Within the tools.ts file, I have defined several functions that I export using export const. One of them is the helloWorld function: export const hel ...

Encountering difficulties in creating a custom Response type in Express.js with TypeScript

I have encountered a TypeScript error while trying to create my own custom Response interface by extending some methods instead of using the default Response type of Express.js: The last overload resulted in the following error: Argument of type '(r ...

Handlebar files are not compatible with Typescript loading capabilities

I am encountering an issue with my directory structure as follows : src |- server |- myServer.ts |- views |- myView.hbs dist |- server |- myServer.js The problem lies in the fact that the dist folder does not have a views subfolder, where the J ...

Tips for ensuring that CSS hover effects stay in place even when the page is scrolled

i'm having trouble with a project in React JS that I received from another team. I'm not very confident in my skills with React JS, and I'm facing an issue where a certain part of the page is supposed to change to red when hovered over. Howe ...