LoginSignup
shio-max
@shio-max (Riooo)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

dispatch is not a function が解決できません!

解決したいこと

フロントエンドをReact, Redux、
バックエンドをFirebaseで ログイン機能を実装しています。
Firebase Authのgoogleログインを実装するのに、signInWithPopup(providerGoogle)で認証し、そのuserデータをFirestoreに作成し、alertの表示まではうまくいくのですが、
その後のHomeページに遷移でエラーが発生します。

発生している問題・エラー

TypeError: dispatch is not a function

該当するソースコード

<GoogleLoginButton onClick={googleLogin()}>
   <span style={{ fontSize: 16 }}>Googleでログイン</span>
</GoogleLoginButton>
export const googleLogin = () => {
  return async (dispatch) => {
    fb.auth()
      .signInWithPopup(providerGoogle)
      .then((result) => {
        //const token = result.credential.accessToken;
        //console.log(token);

        const user = result.user;
        console.log(user);

        if (user) {
          const timestamp = FirebaseTimestamp.now();
          user.providerData.forEach((profile) => {
            // console.log("  Provider-specific UID: " + profile.uid);
            //console.log("  Name: " + profile.displayName);
            //console.log("  Email: " + profile.email);
            const uid = profile.uid;
            const userInitialDataByGoogle = {
              username: profile.displayName,
              email: profile.email,
              role: "customer",
              uid: uid,
              created_at: timestamp,
              updated_at: timestamp,
            };
            db.collection("users")
              .doc(uid)
              .set(userInitialDataByGoogle)
              .then(() => {
                alert("ログインに成功しました");
                dispatch(push("/"));
              });
          });
        }
      })
      .catch((error) => {
        // Handle Errors here.
        var errorMessage = error.message;
        alert(errorMessage);
      });
  };
};

自分で試したこと

メースアドレス&パスワードによる認証の実装はページ遷移まで問題なく動きました。
Actionありでの処理も試してみましたが、同じエラーが出ました。
関数に渡す引数の問題なのかとも思っていますが、、 
dispatchでのページ遷移以外の方法でも良いのでアドバイスよろしくお願い致します。
"https://github.com/deatiger/ec-app-demo" を参考にしております。

0

2Answer

onClick={googleLogin()} では動きません。以下のように useDispatch() で作った dispatch を使ってください。

function Xxx() {
  const dispatch = useDispatch();
  return (
    <GoogleLoginButton onClick={() => dispatch(googleLogin())}>
      <span style={{ fontSize: 16 }}>Googleでログイン</span>
    </GoogleLoginButton>
  );
}

参考 https://react-redux.js.org/api/hooks#usedispatch

2

Comments

  1. @shio-max

    Questioner
    ご回答ありがとうございます。
    イベントハンドルの関数の方は見落としてました。
    ご指摘の通りしてみたら、無事ページ遷移できました!

勘ですが、下記のコードによると、const dispatch = useDispatch();してないからかも?

下記のようにしたらどうでしょうか。

export const googleLogin = () => {
  const dispatch = useDispatch();
  return async (dispatch) => {
0

Comments

  1. @shio-max

    Questioner
    それが原因だったみたいです、、
    ありがとうございます。

Your answer might help someone💌