Search code examples
reactjsgraphqlapollouse-effect

How do I make a query in useEffect() to avoid InvalidHookError?


I'm trying to query an api to get user permissions AFTER logging the user in. But InvalidHookError occurs if I write the useQuery() inside useEffect() as it break React's rules of hooks.

const OnHeader = () => {
    const [user, loading, error] =
        typeof window !== "undefined" ? useAuthState(firebase.auth()) : [null, true, null]
    useEffect(() => {
        if (user) {
            user.getIdToken().then(idToken => {
                localStorage.setItem("accessToken", idToken)
            })
            // todo: query permissions and set them in localstorage
            // but if I put useQuery() here it breaks the rules
        }
    }, [user])

}

My current workaround is using another constant userLoggedIn to detect if a user is logged in. But I'm wondering if there's a better way to write this?

const OnHeader = () => {
    const [user, loading, error] =
        typeof window !== "undefined" ? useAuthState(firebase.auth()) : [null, true, null]
    const [userLoggedIn, setUserLoggedIn] = useState(false)

    var p = useQuery(
        gql`
            query QueryPermissions {
                permissions {
                    action
                    isPermitted
                }
            }
        `,
        {
            skip: !userLoggedIn,
            onCompleted: data => {
                localStorage.setItem("permissions", JSON.stringify(data))
            },
        }
    )

    useEffect(() => {
        if (user) {
            user.getIdToken().then(idToken => {
                localStorage.setItem("accessToken", idToken)
                setUserLoggedIn(true)
            })
        }
    }, [user])
}

Solution

  • The problem is not in the useEffect but in your call to useAuthState. You're breaking the rules of hooks by calling a hook conditionally which is a no-no. Remove the conditional call and put the default values into your custom hook.