我可以記錄 onAuthStateChanged 的??值,但是當我回傳它時,extraReducers 似乎沒有得到它。功能檢查身份驗證狀態
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 始終回傳未定義。我該如何解決?
祝大家擁有美好的一天!
uj5u.com熱心網友回復:
onAuthStateChanged是一個異步呼叫,但它本身不回傳承諾。即使這樣做了,您也不會從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);
}
});
});
}
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/363613.html
