Why is my firebase user returning null inside props with reactjs?

Viewed 13

I am using the following code to obtain a bearer token from firebase which is then sent in the authorization header to the backend.

    const user = firebase.auth().currentUser
    const idToken = await user.getIdToken()

It works well on most of my reactjs requests, however on one page the request is inside props and i am receiving the following error:

Uncaught (in promise) TypeError: user is null

Sometimes when i refresh the page it works, but 99% of the time it fails which is very odd. The code i am using is below:

const Routing = (props) => {
    let uid = localStorage.getItem("account-info");
    let { id } = useParams();

    const loadBlockchainData = async () => {
        const { dispatch } = props;
        if (id === null || id === undefined) {
            id = "test";
        }
        const user = firebase.auth().currentUser
        const idToken = await user.getIdToken()
        var res = await axios.post(backUrl + "account/load_balance", { 
        uid: uid,
        id: id 
          },
          {
          headers: {
          Authorization: 'Bearer ' + idToken
           }});
        if (res.data === null) {
            document.location.href = "/logout"
            return;
        }
        else {
            localStorage.setItem("account-address", res.data.address);
            dispatch(web3AccountLoaded(res.data.address));
            if (res.data.token_flag && res.data.exchange_flag) {
                await dispatch(setLoginUserName(res.data.name));
                await dispatch(setLoginUserEmail(res.data.email));
                if (res.data.balance !== null) {
                   // redacted
                }
            }
            else {
                Swal.fire({
                   // redacted
                });
                return;
            }
        }
    };

    useEffect(() => {
        if (uid) {
            async function fetchData() {
                await loadBlockchainData();
            }
            fetchData();
        }
    }, [uid]);

    return (
        <>
            {uid ? (
                <div>
                    {
                        props.contractsLoaded ? <Exchange id={id} /> : <></>
                    }
                </div>
            ) : (
                <Login />
            )}
        </>
    );
};

How can i fix this?

0 Answers
Related