2

I'm trying to use firebase for authentication in my react redux app. I want to redirect user to next page on successful login but I'm getting the error when I submit the login form

Error

Cannot read property 'then' of undefined

Handle Submit function in LoginForm

handleFormSubmit(event) {
    event.preventDefault();
    if (this.props.email !== '' && this.props.password !== '') {
      this.props.loginUser(this.props.email, this.props.password)
      .then(() => {
        this.context.router.push('/posts');
      });
    } else {
      console.log('empty');
    }
  }

Action Creator

export function loginUser(email, password) {
  return (dispatch) => {
    dispatch({ type: LOGIN_USER });
    firebase.auth().signInWithEmailAndPassword(email, password)
      .then(user => loginUserSuccess(dispatch, user))
      .catch(() => {
        console.log('failed to sign in');
        return;
      });
  };
}


export function loginUserSuccess(dispatch, user) {
  dispatch({
    type: LOGIN_USER_SUCCESS,
    payload: user
  });
}

The authentication works if I remove the then from handle submit function but I don't know how to redirect user to next page ?

2 Answers 2

3

I was able to fix the issue by including a return inside the dispatch. I'm putting the updated code here for future visitors.

export function loginUser(email, password) {
  return (dispatch) => {
    dispatch({ type: LOGIN_USER });
    return firebase.auth().signInWithEmailAndPassword(email, password)
      .then(user => loginUserSuccess(dispatch, user))
      .catch(() => {
        console.log('failed to sign in');
        return;
      });
  };
}

Thanks.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes this is the solution I was going to post. The reason you were getting the error is you weren't returning a Promise.
0

OP didn't mention it, but for those using react-redux-firebase and it's integration with redux-thunk, it would look like so:

export function loginUser(email, password) {
  return (dispatch, { getFirebase }) => {
    return getFirebase()
      .login({ email, password }
      .catch(() => {
        console.log('failed to sign in');
        return;
      });
  };
}

That said, login should be able to be called directly in your components if you are using firebaseConnect or withFirebase as shown in the auth section of the docs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.