I try to persist the redux store state with the currentUser from the Firebase Auth. When I try to access auth.currentUser I get null and I think it's because the currentUser info is loaded asynchronously. What I want is to make my application wait until I fetch the currentUser and then to load the currentUser inside the redux store to access it in my application.
Store.js
import { auth } from "../firebase"
const preloadedState = {
account: auth.currentUser
}
export const store = createStore(
reducers,
preloadedState,
composeEnhancers(applyMiddleware(thunk)),
)
Firebase.js
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
How should I wait for currentUser to be fetched and then load inside the redux store to keep the user authenticated?
According to the documentation, you're supposed to use an auth state observer to get a callback when the user state changes. You can use this information to update your store. (Don't think about this as "waiting" for information - you are respond to changes in state when they happen.)
Attach the observer using the onAuthStateChanged method. When a user successfully signs in, you can get information about the user in the observer.
import { getAuth, onAuthStateChanged } from "firebase/auth"; const auth = getAuth(); onAuthStateChanged(auth, (user) => { if (user) { // User is signed in, see docs for a list of available properties // https://firebase.google.com/docs/reference/js/firebase.User const uid = user.uid; // ... } else { // User is signed out // ... } });