I have a firebase app with react. I want the login state to be persistent even after page refresh. Currently when I refresh the page my redux slice goes back to it's initial state.
My firebaseConfig file:
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: "AIzaSyDJECv1Q0Jal7-j8z1xxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxx",
appId: "1:974xxxxxxxxxxxxxxxx"
};
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
//auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL);
export default app;
My redux authSlice:
import { createSlice } from "@reduxjs/toolkit";
import { GoogleAuthProvider, signOut, onAuthStateChanged, signInWithPopup} from "firebase/auth"
import { auth } from "../../config/firebaseConfig";
const authSlice = createSlice({
name: 'auth',
initialState: {
uid : null,
email: null,
displayName : null,
photoURL : null,
},
reducers: {
removeUser(state, action) {
state.uid = null;
state.email= null;
state.displayName = null;
state.photoURL = null;
},
addUser(state, action){
state['uid'] = action.payload.uid;
state['email'] = action.payload.email;
state['displayName'] = action.payload.displayName;
state['photoURL'] = action.payload.photoURL;
}
}
});
export const { removeUser, addUser } = authSlice.actions;
export default authSlice.reducer;
export function signInWithGoogle(){
return async (dispatch) => {
try {
const googleAuthProvider = new GoogleAuthProvider();
const result = await signInWithPopup(auth, googleAuthProvider);
console.log(result.user);
dispatch(addUser(result.user));
} catch (error) {
alert(error.message);
}
}
}
export function logout(){
return async (dispatch) => {
try {
await signOut(auth);
dispatch(removeUser())
} catch (error) {
alert(error.message);
}
}
}
I have tried adding : auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL);
in my firebaseConfig file. but it's throwing an error saying: [2023-02-21T20:54:26.489Z] @firebase/auth: Auth (9.17.1): INTERNAL ASSERTION FAILED: Expected a class definition