i am trying to get current user in console but getting undefined in react-native. firebase 8.3 it is. this is my firebase init
import firebase from "firebase";
// import { initializeApp } from "firebase/app";
const firebaseConfig = {
//api
};
// Initialize Firebase
const app = firebase.initializeApp(firebaseConfig);
export default firebase;
this is action code , which is same as docs in internet
firebase
.firestore()
.collection("user")
.doc(firebase.auth().currentUser.uid)
.get()
.then((snapshot) => {
if (snapshot.exists) {
console.log(snapshot.data());
dispatch({ type: USER_STATE_CHANGE, currentUser: snapshot.data() });
} else {
console.log("does not exist, console from action ");
}
and here is my redux store code, which is more doubtful in my knowledge
const store = createStore(Reducers, applyMiddleware(thunk))
return (
<Provider style={styles.center} store={store}>
<Main/>
</Provider>
);
and main.js
function Main(props) {
useEffect(() => {
props.fetchUser();
}, []);
if (props.currentUser == undefined) {
return (
<View>
<Text>No Data</Text>
</View>
);
} else {
return (
<View>
<Text>{props.currentUser.name} is logged in now !</Text>
</View>
);
}
}
const mapStateToProps = (state) => {
return {
currentUser: state.user.currentUser,
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchUser: () => dispatch(fetchUser()),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Main);
My guess (it is hard to be certain from the fragments of code you shared) is that the code that loads the user data from Firestore runs when the page/app loads, and that Firebase isn't done restoring the current user when it runs.
When the page/app loads, Firebase automatically restores the user credentials from local storage. This requires it to call the server though (amongst others to see if the account has been disabled), which may take some times. While this call is going on, your main code continues, and the value of firebase.auth().currentUser is null at this point.
So if you don't synchronize your code that loads the user profile to Firebase''s restore actions, you will end up loading the data too early, when the user hasn't been re-signed yet.
The solution is to listen for auth state changes, and respond to those, instead of assuming that firebase.auth().currentUser is always correct. For an example of how to do this, see the first code snippet in the Firebase documentation on getting the current user:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user.uid;
// 🤞 This is where you can load the user profile from Firestore
// ...
} else {
// User is signed out
// ...
}
});