【问题标题】:onAuthStateChanged return undefinedonAuthStateChanged 返回未定义
【发布时间】:2022-01-01 14:39:13
【问题描述】:

我可以记录 onAuthStateChanged 的​​值,但是当我返回它时,extraReducers 似乎没有得到它。 功能检查auth的状态

import { createAsyncThunk, createSlice} from "@reduxjs/toolkit";
import {
  onAuthStateChanged,
  signOut
} from "firebase/auth";
export const checkUserSignIn = createAsyncThunk(
  "auth/checkUSerSignIn",
  async () => {
    const auth = getAuth();
    onAuthStateChanged(auth, (user) => {
      if (user) {
        console.log(user)
        return true
      } else {
        return false
      }
    });
  }
);

我在哪里得到返回值

const authSlice = createSlice({
  name: "auth",
  initialState: {
    auth: {
      isLoading: false,
      isAuthenticate: false,
      user: null,
    },
  },
  reducers: {},
  extraReducers: (builder) => {
    //Check User SignIn
    builder
      .addCase(checkUserSignIn.pending, (state, action) => {
        state.auth.isLoading = true;
        console.log(`CheckUserSignIn Pending: ${action.payload}`);
      })
      .addCase(checkUserSignIn.fulfilled, (state, action) => {
        state.auth.isLoading = false;
        action.payload
          ? (state.auth.isAuthenticate = true)
          : (state.auth.isAuthenticate = false);

        console.log(`CheckUserSignIn Fulfilled: ${action.payload}`);
      })
      .addCase(checkUserSignIn.rejected, (state, action) => {
        console.log(`CheckUserSignIn Rejected: ${action.error.message}`);
      });
    
    
  },
});

已完成案例的action.payload 始终返回未定义。我该如何解决?

祝大家有个愉快的一天!

【问题讨论】:

    标签: reactjs firebase redux


    【解决方案1】:

    onAuthStateChanged 是一个异步调用,但它本身并不返回一个 Promise。即使这样做了,您也不会从 checkUserSignIn 函数的顶级代码中返回任何内容。

    这可能更接近您需要/想要的:

    export const checkUserSignIn = createAsyncThunk(
      "auth/checkUSerSignIn",
      async () => {
        return new Promise((resolve, reject) {
          const auth = getAuth();
          const unsubscribe = onAuthStateChanged(auth, (user) => {
            unsubscribe();
            if (user) {
              resolve(true);
            } else {
              resolve(false);
            }
          });
        });
      }
    );
    

    【讨论】:

    • @Downvoter:请解释一下我的回答没有什么用处,以便我改进。
    猜你喜欢
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 2016-11-18
    • 2019-12-24
    • 2016-05-15
    相关资源
    最近更新 更多