Search code examples
javascriptreactjsredux-thunk

Dispatch in Redux-Thunk


Uncaught (in promise) Error: Request failed with status code 400

I need to make a page request to the database for logging into the system, but I'm already too confused and don't know how to remove this error. Before that there was the error "Actions must be plain objects. Use custom middleware for async actions." After that I connected Redux-Thunk and the current error appeared.

Actions

export const auth = (email, password, isLogin) => {
  return async(dispatch) => {
    dispatch(authData())
    
    let url = 'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyAU8gNE0fGG8z9zqUyh68Inw9_RzljhCCs'

    if (isLogin) {
      url = 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyAU8gNE0fGG8z9zqUyh68Inw9_RzljhCCs'
    }
    const response = await axios.post(url, authData)
    console.log(response.data)
  }
}

const authData = (email, password, returnSecureToken = true) => ({
  type: 'LOGIN',
  email,
  password,
  returnSecureToken
})

Component

loginHandler = () => {
  this.props.auth(
    this.props.AuthMail,
    this.props.AuthPass,
    true
  )
}

registerHandler = () => {
  this.props.auth(
    this.props.AuthRegMail,
    this.props.AuthRegPass,
    false
  )
}

const mapDispatchToProps = dispatch => {
  return {
    auth: (email, password, isLogin) => dispatch(auth(email, password, isLogin))
  }
}

Solution

  • // You forgot to add the arguments to authData function
    dispatch(authData())
    // Here you are passing in a function as the second argument
    const response = await axios.post(url, authData)
    

    Should probably be something like this:

    export const auth = (email, password, isLogin) => {
      return async (dispatch) => {    
        const url = isLogin ? 'example.com/login' : 'example.com/signup';
        const response = await axios.post(url, {
          email,
          password,
          returnSecureToken: true,
        });
        console.log(response.data);
        // Handle this action somewhere to store the signed in user data in redux
        dispatch({
          type: "LOGIN",
          payload: response.data
        })
      }
    }