Etherealm
Etherealm

Reputation: 2484

Firebase authentication with React Redux Redux-Thunk

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 ?

Upvotes: 2

Views: 1759

Answers (2)

Scott
Scott

Reputation: 1615

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.

Upvotes: 0

Etherealm
Etherealm

Reputation: 2484

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.

Upvotes: 3

Related Questions