user1088793
user1088793

Reputation: 653

Invalid hook call. Hooks can only be called inside of the body of a function component. Any ideas?

I have honestly trawled through the existing questions for the answer, but this one is a total mystery.

Firebase.js

import * as firebase from "firebase/app";
import "firebase/auth";
import React, { useContext } from "react";
import { Auth } from "../contexts/AuthContext";

export const FirebaseLogout = async () => {
  const { state: auth, dispatch } = useContext(Auth);
  const logout = await firebase
    .auth()
    .signOut()
    .then(
      dispatch({
        type: "LOGOUT",
      })
    )
    .catch((err) => {
      console.log(err);
      return err;
    });
  return;
};

MyPage.js

import { FirebaseLogout } from "../../../firebase/Firebase";
...Stateless functional component with other non-relevant code between...
<Button onClick={() => FirebaseLogout()} type='primary'>
  {auth.user.uid ? "Logout" : "Sign up"}
</Button>

Upvotes: 1

Views: 362

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281686

FirebaseLogout is an action or an handler and hence can't use the useContext hook. The solution is to either make it into a custok hook or pass in the context value as argument

export const FirebaseLogout = async () => {

  const logout = await firebase
    .auth()
    .signOut()
    .then(
      dispatch({
        type: "LOGOUT",
      })
    )
    .catch((err) => {
      console.log(err);
      return err;
    });
  return;
};

MyPage.js

const contextValue = useContext(Auth);


  <Button onClick={() => FirebaseLogout(contextValue)} type='primary'>
     {auth.user.uid ? "Logout" : "Sign up"}
   </Button>

Upvotes: 2

Related Questions