Search⌘ K
AI Features

Async Error Handling Logic in Thunks

Explore how to manage asynchronous error handling in Redux Toolkit thunks by using try-catch blocks, dispatching failure actions, and updating the UI to reflect errors during data fetching.

We'll cover the following...

Introduction

As you’ll come to see, handling errors in thunks is just as straightforward as the loading state handled in the last lesson.

Let’s get right into it. But first, here’s the flow we’re gunning for within the fetchTweets thunk:

  • Wrap API call in a try-catch block.
  • Catch errors if they occur and dispatch a new action.
  • Save error message.
  • Handle error state in the application UI.
// before 
export const fetchTweets = (searchValue, numberOfResults) => async (
  dispatch
) => {
  dispatch(isLoadingTweets());
  const tweets = await findTweets(searchValue, numberOfResults);
  dispatch(loadingTweetsSuccess(tweets));
};


// now 
export const
...