Reputation: 819
I'm new to whole react redux world but I would like to think that I now know how redux works. However right now I'm facing a new challange I need to implement async data fetching. I've choose to use axios as my http client.
The problem I have right now is that I've read about redux async thunk but I have no idea when and why would I use it. I understand that it adds middleware to redux which can handle async/await and promises.
I want to simply use axios to get data and then use dispatch to store them. Like this
const loadData = async () => {
const res = await axios.get('https://www.api.com/mydata');
const data = res.data;
dispatch(setMyData(data));
}
How would createAsyncThunk
help me with that?
Upvotes: 6
Views: 1333
Reputation: 2925
In your example, loadData
only waits for one api request and then dispatches one simple redux action (setMyData
). If you need it exactly like this, you're correct, why would you need thunks?
But imagine the following:
setMyData()
.All of these are common requirements for complex react/redux apps, you might not have them right now but are likely to run into them at some point.
The thunk middleware provides an abstraction that deals with them. You could achieve the same by writing your own helper functions etc. but you'd reinvent the wheel in the end and a lot of react/redux devs would end up writing the exact same boilerplate code.
Upvotes: 8
Reputation: 288
By design, redux actions are meant to be synchronous. Adding thunks like redux-thunk
allow you to write action creators that are async and therefore return promises.
For example, I can write an action creator that looks like this:
const getUsers = () => async dispatch => {
let users = await getUsers();
dispatch({
type: GET_USERS,
payload: users
});
}
So instead of calling an api, fetching data, and then dispatching an action, you can have an action that does the fetching inside it
Upvotes: 0