Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my try catch block handle dispatch error?

I can't get a rejected promise in my try catch block, it's response is always in the originalPromiseResult

Here is the slice where I get some data from the API:

export const getData = createAsyncThunk(
  'user/getData',
  async (headers, { rejectWithValue }) => {
    try {
      return await httpService.getData(headers)
    } catch (err) {
      console.error(e)
      return rejectWithValue(err.response.data)
    }
  }
)

And here is my component:

const dispatch = useDispatch()

const myCallback = async (data) => {
    try {
      const originalPromiseResult = await dispatch(getData(data))
    } catch (error) {
      console.log('error = ', error)
    }
}
like image 349
user3189117 Avatar asked Apr 24 '26 03:04

user3189117


1 Answers

createAsyncThunk always handles all thrown errors internally - otherwise you'd see a lot of "uncaught rejected Promise" warnings in your console. That means it also always returns a resolved Promise, containing the action that was dispatched.

Per our docs, if you want to do a try/catch at the component level based on the dispatch, you need to "unwrap" the returned promise. This will either return the payload if a fulfilled action was dispatched, or re-throw the error if the rejected action was dispatched.

    try {
      const originalPromiseResult = await dispatch(getData(data)).unwrap()
    } catch (error) {
      console.log('error = ', error)
    }

Reference:

https://redux-toolkit.js.org/api/createAsyncThunk#unwrapping-result-actions

like image 132
markerikson Avatar answered Apr 29 '26 08:04

markerikson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!