Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

javascript - This custom async hook is not working as expected

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...