Tuesday, 30 April 2019

How to use redux-promise-middleware with react-scripts v3

I recently updated my react-scripts to version 3.0.0 in my React application and all of my actions stopped working.

I am using redux-promise-middleware so I have always this pattern when fetching data:

export const FIRST_ACTION = 'FIRST_ACTION';
export const FIRST_ACTION_PENDING = 'FIRST_ACTION_PENDING';
export const FIRST_ACTION_REJECTED = 'FIRST_ACTION_REJECTED';
export const FIRST_ACTION_FULFILLED = 'FIRST_ACTION_FULFILLED';

store.js:

import promiseMiddleware from 'redux-promise-middleware';

export default function configureStore() {
    return createStore(
        rootReducer,
        applyMiddleware(thunk, promiseMiddleware(), logger)
    );
}

I am usually performing several requests in a chain in my actions like this:

import { 
    firstAction,
    secondAction
} from '../service';

const chainedAction = (...) => {
    return (dispatch) => {
        return dispatch({
            type: FIRST_ACTION,
            payload: firstAction(...)
        }).then(() => dispatch({
            type: SECOND_ACTION,
            payload: secondAction(...)
        }));
    };
};

After the update, I am getting the following errors:

React Hook "firstAction" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function  react-hooks/rules-of-hooks

Does anybody know how to migrate my actions so they will be compliant with the latest dependencies?

EDIT: I am importing this action in my react component and calling it from there:

import { 
    chainedAction
} from '../actions';
...
<Button onClick={(...) => chainedAction(...)}
...
const mapDispatchToProps = dispatch => (
    bindActionCreators({ 
        chainedAction
    }, dispatch)
);

export default connect(mapStateToProps, mapDispatchToProps)(MyPage);

firstAction (second action is similar):

export const firstAction = (...) => {
    return new Promise((resolve, reject) => {
        fetch(API_URL, {
            method: 'POST',
            body: ...
        }).then(response => {
            if (response.ok) {
                resolve(response.text());
            }

            reject('...');
        }).catch(error => {
            return reject(error.message);
        });
    });
};



from How to use redux-promise-middleware with react-scripts v3

No comments:

Post a Comment