Home > OS >  Why do I need redux async thunks
Why do I need redux async thunks

Time:11-02

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?

CodePudding user response:

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:

  • Several components in your app need to be aware that this api request is in progress (for example to show a loading indicator or to hide a button)
  • This function is needed in more than one place
  • You need to deal with specific error responses to the api request
  • Something in the global redux state could have changed while waiting for the api request to finish. You need to react to this before dispatching 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.

CodePudding user response:

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

  • Related