简体   繁体   中英

How to dispatch Redux action from Firebase auth in React Native

I am trying to dispatch a logIn function using the firebase auth listener, as per the docs. But I want to use the listener to trigger a redux action to populate my state.

When I try and run the following code, upon successfully logging in with firebase, it fails with "Cannot read property 'logIn' of undefined.

Please halp

 class RootApp extends Component { componentWillMount() { // Listen for Auth Changes firebase.auth().onAuthStateChanged(function(user) { if (user) { this.props.logIn( uid, displayName, photoURL, providerId, email, emailVerified ); // User is signed in. } else { console.log("Not logged in"); // No user is signed in. } }); } render() { if (this.props.auth.checking == true) { return ( <ActivityIndicator animating={true} style={styles.activityIndicator} size="large" /> ); } else if (this.props.auth.signedIn == true) { return <SignedIn />; } else { return <SignedOut />; } } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#fff", alignItems: "center", justifyContent: "center", fontSize: 96 }, activityIndicator: { flex: 1, justifyContent: "center", alignItems: "center", height: 80 } }); const mapStateToProps = state => { return { auth: state.auth }; }; const mapDispatchToProps = dispatch => { return { logIn: ( uid, displayName, photoURL, providerId, email, emailVerified ) => { dispatch( logIn( uid, displayName, photoURL, providerId, email, emailVerified ) ); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(RootApp); 

For others that strike this, the answer was to convert the firebase example listener function to a fat arrow function, as the old fashioned function used in their example bound it's own 'this', which arrow functions don't do.

So this:

firebase.auth().onAuthStateChanged(function(user) {

Needs to be changed to:

firebase.auth().onAuthStateChanged(user => {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM