Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have this custom hook to get the current user from firebase:

import React, { Component, useEffect, useState } from 'react';
import { auth } from "../firebase/auth-service"

const useFirebaseAuthentication = (firebase) => {
    const [authUser, setAuthUser] = useState(null);

    try {
        auth.onAuthStateChanged(async user => {
            if (user) {
                setAuthUser(user)
            } else {
                setAuthUser(null);
            }
        })
    } catch (error) {
        throw error
    }

    return authUser
}

export default useFirebaseAuthentication;

When I print on the screen the current user from this custom hook - I get the result as expected. When I use the hook and try to get the user - I get null.

Can someone point out my mistake?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
4.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

I don't think that useState here is appropriate, don't you get any console warnings? A hook is just a js function as any other, it's not a React component!

Try to use a local variable instead...

edit

useState is a hook, therefore you should be getting this warning:

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See for tips about how to debug and fix this problem.

It's exactly what's a problem here: you use a hook NOT inside the body of a react functional component, you use it in an ordinary js function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...