简体   繁体   中英

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?

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.

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