简体   繁体   中英

TypeError: currentUser is null in firebase react

I found different already answered questions to my question, but the don't help.

I use a custom context to call the firebase.auth().onAuthStateChanged() and set the currentUser .

import React, { useState, useEffect } from "react";
import app from "../firebase";

export const AuthContext = React.createContext();

export const AuthProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);

  useEffect(() => {
    app.auth().onAuthStateChanged(setCurrentUser);
  }, []);

  return (
    <AuthContext.Provider value={{ currentUser }}>
      {children}
    </AuthContext.Provider>
  );
};

In my component I call the AuthContext and the currentUser :

import React, { useContext, useEffect, useState } from "react";
import app from "./firebase";
import { AuthContext } from "./Auth/Auth";

function MyComponent() {
  const [invoices, setInvoices] = useState([]);
  const { currentUser } = useContext(AuthContext);

  const getInvoices = () => {
    const database = app.firestore();
    const unsubscribe = database
      .collection("invoices")
      .where("uid", "==", currentUser.uid) // HERE currentUser IS NULL
      .orderBy("date", "desc")
      .onSnapshot((snapshot) => {
        setInvoices(
          snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() }))
        );
      });

    return () => {
      unsubscribe();
    };
  };

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

  return (<> ... </>);
}
export default MyComponent;

I believe my issue has something to do with promises and the user is not yet loaded. But still I don't know what to do here.

The potential issue could be the value of currentUser returns a bit later so you need to add an extra check in your MyComponent component.

I would add null check for currentUser and extend the dependency array as:

useEffect(() => {
  if (currentUser) {
     getInvoices();
  }
}, [currentUser]);

Probably in the first round the useEffect callback was running once currentUser was still null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM