Search code examples
promisereduxredux-thunk

cannot get a promise after bindActionCreators in Redux


I use react/redux to create an app.

I've a custom action creator to make an async request (I use redux-thunk).

export function loginAttempt(userData) {
  return dispatch => {

    let formData = new FormData();
    formData.append('username', userData.username);
    formData.append('password', userData.password);

    fetch('https://api.t411.ch/auth', {
      method: 'POST',
      body: formData
    }).then(response => {
      if (response.status !== 200) {
        const error = new Error(response.statusText);
        error.respone = response;
        dispatch(loginError(error));
        throw error;
      }
      return response.json();
    }).then(data => {
       dispatch(loginSuccess(data));
    });
  }

In my component, I use bindActionCreators to bind this method with dispatch :

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';


import SearchBar from './SearchBar';
import TorrentLayout from './TorrentLayout';

import * as LoginActions from '../actions/login'; // <---- it's where the code above is located
import * as SearchActions from '../actions/search'; 


function mapStateToProps(state) {
  return {
    login: state.login,
    searching: state.searching
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({...LoginActions, ...SearchActions}, dispatch);
}

@connect(mapStateToProps, mapDispatchToProps)
export default class Home extends Component {

  constructor(props) {
    super(props);

    console.log('should be a promise');
    let foobar = this.props.loginAttempt({username: 'username', password:'password'});

    console.log(foobar); // <------ undefined

    // that I want to do
    this.props.loginAttempt({username: 'username', password:'password'}).then(() => {
        this.props.search(this.props.login.token, "mysearch");
    }
  }

  render() {
    return (
      <div>
        <div>
           <SearchBar {...this.props} />
           <TorrentLayout {...this.props}/>
        </div>
      </div>
    );
  }
}

I would like to apply 'then' to my action creator already bound to dispatch.

Thanks


Solution

  • You need to return fetch() inside your arrow function inside loginAttempt. Like so:

    export function loginAttempt(userData) {
      return dispatch => {
        return fetch('https://api.t411.ch/auth', {
          method: 'POST',
          body: formData
        }).then(...);
      }
    

    Basically when you call your binded action creator the arrow functions gets executed but it doesn't have a return value.