Why is there Actions must be plain objects without ReduxThunk?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
110 views
Hello
Such AC asynchronous request processing :

export const searchAction = (val:string) => async dispatch => { const root:string = "https://images-api.nasa.gov/"; const res = await axios.get(`${root}/search?q=${val}`); return dispatch({ type: consts.SEARCH_INIT, payload: res }) };


Error : Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
But I return an ordinary object in the variable res. Why then the code doesn't work without ReduxThunk?
Thank you
by | 110 views

1 Answer

0 like 0 dislike
Because redux-thunk is a middleware and if you look at his source code(only 14 lines), you would see that it intercepts and invokes the function by passing in the necessary arguments and returns the result without betraying it further. Without him to stop them nothing and they get there where you do not have to go and provoke an error, as Redux without мiddleware at the entrance to the dispatch takes only objects, and as stated in the text of the erroryou receive.

The return value(return) for the asynchronous action is used only by you, it returns the call to dispatch. In reduceri, as was mentioned above, it misses.
Since it returns Promise, you can use something like this:
Your Async action:
export const asyncAction = (...someArgs) => async dispatch => { const res = await someAsyncCall(...someArgs); dispatch({ type: SOME_ACTION_TYPE, payload: res }); return res; };

Use in the code(a clear example of the dispatch):
componentDidMount() { const { dispatch } = this.props; dispatch(asyncAction(...optionalArgs)).then(result => doSomething(result)); }

Same with proposal async action using connect:
componentDidMount() { const { asyncAction } = this.props; asyncAction(...optionalArgs).then(result => doSomething(result)); }


In General, for use then the value from the asynchronous function to return not necessarily and also this code will work fine:
export const asyncAction = (...someArgs) => async dispatch => { const res = await someAsyncCall(...someArgs); dispatch({ type: SOME_ACTION_TYPE, payload: res }); };

Use in the code(a clear example of the dispatch):
componentDidMount() { const { dispatch } = this.props; dispatch(asyncAction(...optionalArgs)).then(() => doSomething()); }
by
110,608 questions
257,186 answers
0 comments
35,456 users