1
votes

So I want to understand beyond the basics of Redux thunk and I made two action creators, one of which works and uses redux thunk and other which only uses async but breaks.Below is the screenshot: 

screenshot

So in both action creators I await for the API request to finish and then return an action ( a JS object with type and payload).

However only the top one works and the bottom one gives an error saying action must be plain object although I return a plain object with 2 properties. I've been really struggling to understand why does the second action creator brakes and would be really nice if someone could explain in details why is it happening.Thank you!

2
"although I return a plain object with 2 properties" no you don't. Async function returns a promise that is resolved to whatever you return. So the message is correct, your action creator returns a promise and you don't have a middleware to handle it.Yury Tarabanko
Please include all the relevant code in the question itself. Images of code are not searchable making the question not useful for future readers.Yury Tarabanko

2 Answers

2
votes

It is because, when you use thunk, you return either an object or function. In 2nd case, when you dispatched your actions something like this dispatch(fetchUser()), it didn't return any thing because you are calling an async method. Now code below await will only be executed once async all is done, original call of dispatch(fetchUser()) is already completed (hint : Only code below await is not executed, but the function call is already over), and fetchUser() didn't return any object, but in first case, you are actually returning a function which is calling an async method. This is where the magic of thunk middleware really happens. It executes that function and dispatch an action (hint: you are returning a function which is taking dispatch as an argument) which is executed by thunk. Hope this clears your doubt. I would suggest you to read how async/await really works (hint : event loops/single threaded).

0
votes

You cant use an async function because it will always returns a promise. Even if you return a value it will be wrapped in a promise and it is returned. If you dont return anything in async function and try to read the value , then undefined will be wrapped in a promise . As redux says action creators should return a plain object which cannot be done directly using async functions.