Michal Kurz
Michal Kurz

Reputation: 2095

Is there a way to make `endpoint.initiate()` always throw on failed request?

I dispatch a RTKQuery mutation inside a custom thunk like this:

const result = await dispatch(
  commentsApi.endpoints.myEndpoint.initiate(params)
)

and I noticed that when the underlying request fails, this does not throw an exception - the above dispatch call resolves into an object with an error property instead.

What is the reason for that? I would prefer rejecting, so I could use it like this:

try {
  await dispatch(commentsApi.endpoints.myEndpoint.initiate(params))
  someOtherCallDependentOnMutationSuccess()
} catch (e) {
  // ...
}

Is there a way to make all endpoint.initiate() calls reject when the underlying request fails? Or is there a good reason not to want that?

Upvotes: 0

Views: 266

Answers (1)

Rashomon
Rashomon

Reputation: 6762

You can change the logic to make the dispatch throw an error using .unwrap():

try {
  await dispatch(commentsApi.endpoints.myEndpoint.initiate(params)).unwrap()
  // following code will be reached only if previous dispatch succeded
  someOtherCallDependentOnMutationSuccess()
} catch (e) {
  // ...
}

Upvotes: 1

Related Questions