reactjsasynchronousreduxmiddlewarereact-thunk

Why do I need redux async thunks


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?


Solution

  • 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:

    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.