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)
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With