You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Using [`async-mutex`](https://github.com/DirtyHairy/async-mutex) to prevent multiple calls to '/refreshToken' when multiple calls fail with [`401 Unauthorized`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401) errors.
396
+
397
+
```ts title="Preventing multiple calls to '/refreshToken'"
// wait until the mutex is available without locking it
426
+
// highlight-start
427
+
awaitmutex.waitForUnlock()
428
+
// highlight-end
429
+
let result =awaitbaseQuery(args, api, extraOptions)
430
+
if (result.error&&result.error.status===401) {
431
+
// checking whether the mutex is locked
432
+
// highlight-start
433
+
if (!mutex.isLocked()) {
434
+
const release =awaitmutex.acquire()
435
+
// highlight-end
436
+
try {
437
+
const refreshResult =awaitbaseQuery(
438
+
'/refreshToken',
439
+
api,
440
+
extraOptions
441
+
)
442
+
if (refreshResult.data) {
443
+
api.dispatch(tokenReceived(refreshResult.data))
444
+
// retry the initial query
445
+
result=awaitbaseQuery(args, api, extraOptions)
446
+
} else {
447
+
api.dispatch(loggedOut())
448
+
}
449
+
} finally {
450
+
// release must be called once the mutex should be released again.
451
+
// highlight-start
452
+
release()
453
+
// highlight-end
454
+
}
455
+
} else {
456
+
// wait until the mutex is available without locking it
457
+
// highlight-start
458
+
awaitmutex.waitForUnlock()
459
+
// highlight-end
460
+
result=awaitbaseQuery(args, api, extraOptions)
461
+
}
462
+
}
463
+
returnresult
464
+
}
465
+
```
466
+
393
467
### Automatic retries
394
468
395
469
RTK Query exports a utility called `retry` that you can wrap the `baseQuery` in your API definition with. It defaults to 5 attempts with a basic exponential backoff.
0 commit comments