mqliutie mqliutie - 14 days ago 5
Javascript Question

Redux Actions must be plain objects. Use custom middleware for async actions

The code is:

Test component:

import {add} from './../actions/';

class Test extends Component{

_add = (){
this.props.add(1);
}

render(){
<button onClick={this._add}>add</button>
}

}

const mapStateToProps = ()=>({
haha:'haha'
});

export default connect(
mapStateToProps,
{add}
)(Test)


Actions:

export const add = value => (dispatch) =>{
dispatch({
type:'ADD',
value:value
})
}


I click add button there has this error!

What's the issue?

I looked createStore.js and
console.log(action)
. It shows a function.

But Redux's example is not a function. My code is almost the same.

Answer

If you use redux-thunk as a middleware, it will process dispatched function actions....

Another one is redux-promise which will do somethink like the thunk ... but with promises

UPDATE:

This is a model to handle async

export const add = value => (dispatch) => {
   ... do something async
}

LIke this:

export const add = value => (dispatch) => {
   http.get('/path')
       .then(json => 
           dispatch({type: 'RESULT', payload: json}));
}

You action does not have async calls so it could be written like this:

export const add = value => ({
    type:'ADD',
    value:value
})