i can log value of onAuthStateChanged but when i return it, extraReducers seem did not get it. function check state of 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
}
});
}
);
where i get return value
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 of fulfilled case always return undefined. how can i fix it?
have a nice day, everyone!
CodePudding user response:
onAuthStateChanged
is an asynchronous call, but it doesn't return a promise itself. Even if it did, you're not returning anything from the top-level code in the checkUserSignIn
function.
This is probably closer to what you need/want:
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);
}
});
});
}
);