2

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)
    }
}
user3189117
  • 35
  • 1
  • 4

1 Answers1

10

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

Kas Elvirov
  • 7,394
  • 4
  • 40
  • 62
markerikson
  • 63,178
  • 10
  • 141
  • 157
  • thank you for your reply, I tried unwrap before, but it was not a function, so now I'd just tried to use the toolkit's unwrapResult and it worked smooth. wondering why unwrap is not there ... hm – user3189117 Aug 24 '21 at 07:30
  • We added `returnedPromise.unwrap()` in the recent 1.6.0 version - you might want to check what version of RTK you're using and update it: https://github.com/reduxjs/redux-toolkit/releases/tag/v1.6.0 – markerikson Aug 24 '21 at 14:50