Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux-Thunk - Async action creators Promise and chaining not working

I am trying to dispatch an action. I found working examples for some actions, but not as complex as mine.

Would you give me a hint? What am I doing wrong?

I am using TypeScript and have recently removed all typings and simplified my code as much as possible.

I am using redux-thunk and redux-promise, like this:

import { save } from 'redux-localstorage-simple';
import thunkMiddleware from 'redux-thunk';
import promiseMiddleware from 'redux-promise';

const middlewares = [
        save(),
        thunkMiddleware,
        promiseMiddleware,
    ];
const store = createStore(
        rootReducer(appReducer),
        initialState,
        compose(
            applyMiddleware(...middlewares),
            window['__REDUX_DEVTOOLS_EXTENSION__'] ? window['__REDUX_DEVTOOLS_EXTENSION__']() : f => f,
        ),
    );

Component - Foo Component:

import actionFoo from 'js/actions/actionFoo';
import React, { Component } from 'react';
import { connect } from 'react-redux';

class Foo {
    constructor(props) {
        super(props);
        this._handleSubmit = this._handleSubmit.bind(this);
    }
    _handleSubmit(e) {
        e.preventDefault();
        this.props.doActionFoo().then(() => {
            // this.props.doActionFoo returns undefined
        });
    }
    render() {
        return <div onClick={this._handleSubmit}/>;
    }
}

const mapStateToProps = ({}) => ({});

const mapDispatchToProps = {
    doActionFoo: actionFoo,
};

export { Foo as PureComponent };
export default connect(mapStateToProps, mapDispatchToProps)(Foo);

Action - actionFoo:

export default () => authCall({
    types: ['REQUEST', 'SUCCESS', 'FAILURE'],
    endpoint: `/route/foo/bar`,
    method: 'POST',
    shouldFetch: state => true,
    body: {},
});

Action - AuthCall:

// extremly simplified
export default (options) => (dispatch, getState) => dispatch(apiCall(options));

Action - ApiCall:

export default (options) => (dispatch, getState) => {
    const { endpoint, shouldFetch, types } = options;

    if (shouldFetch && !shouldFetch(getState())) return Promise.resolve();

    let response;
    let payload;

    dispatch({
        type: types[0],
    });

    return fetch(endpoint, options)
        .then((res) => {
            response = res;
            return res.json();
        })
        .then((json) => {
            payload = json;

            if (response.ok) {
                return dispatch({
                    response,
                    type: types[1],
                });
            }
            return dispatch({
                response,
                type: types[2],
            });
        })
        .catch(err => dispatch({
            response,
            type: types[2],
        }));
};
like image 828
dazlious Avatar asked Jan 04 '18 21:01

dazlious


2 Answers

From redux-thunk

Redux Thunk middleware allows you to write action creators that return a function instead of an action

So it means that it doesn't handle your promises. You have to add redux-promise for promise supporting

The default export is a middleware function. If it receives a promise, it will dispatch the resolved value of the promise. It will not dispatch anything if the promise rejects.

The differences between redux-thunk vs redux-promise you can read here

like image 116
The Reason Avatar answered Oct 17 '22 09:10

The Reason


Okay, after several hours, I found a solution. redux-thunk had to go first before any other middleware. Because middleware is called from right to left, redux-thunk return is last in chain and therefore returns the Promise.

import thunkMiddleware from 'redux-thunk';

const middlewares = [
        thunkMiddleware,
        // ANY OTHER MIDDLEWARE,
    ];
const store = createStore(
        rootReducer(appReducer),
        initialState,
        compose(
            applyMiddleware(...middlewares),
            window['__REDUX_DEVTOOLS_EXTENSION__'] ? window['__REDUX_DEVTOOLS_EXTENSION__']() : f => f,
        ),
    );
like image 33
dazlious Avatar answered Oct 17 '22 09:10

dazlious