Skip to content

Commit d2f75f6

Browse files
committed
Add docs for timeout
1 parent 4a2ed54 commit d2f75f6

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

docs/rtk-query/api/fetchBaseQuery.mdx

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ description: 'RTK Query > API: fetchBaseQuery reference'
1313

1414
This is a very small wrapper around [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) that aims to simplify requests. It is not a full-blown replacement for `axios`, `superagent`, or any other more heavy-weight library, but it will cover the large majority of your needs.
1515

16-
It takes all standard options from fetch's [`RequestInit`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch) interface, as well as `baseUrl`, a `prepareHeaders` function, an optional `fetch` function, and a `paramsSerializer` function.
16+
It takes all standard options from fetch's [`RequestInit`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch) interface, as well as `baseUrl`, a `prepareHeaders` function, an optional `fetch` function, a `paramsSerializer` function, and a `timeout`.
1717

1818
- `baseUrl` _(required)_
1919
- Typically a string like `https://api.your-really-great-app.com/v1/`. If you don't provide a `baseUrl`, it defaults to a relative path from where the request is being made. You should most likely _always_ specify this.
@@ -38,6 +38,8 @@ It takes all standard options from fetch's [`RequestInit`](https://developer.moz
3838
- A function that can be used to apply custom transformations to the data passed into [`params`](#setting-the-query-string). If you don't provide this, `params` will be given directly to `new URLSearchParms()`. With some API integrations, you may need to leverage this to use something like the [`query-string`](https://github.com/sindresorhus/query-string) library to support different array types.
3939
- `fetchFn` _(optional)_
4040
- A fetch function that overrides the default on the window. Can be useful in SSR environments where you may need to leverage `isomorphic-fetch` or `cross-fetch`.
41+
- `timeout` _(optional)_
42+
- A number in milliseconds that represents that maximum time a request can take before timing out.
4143

4244
```ts title="Return types of fetchBaseQuery" no-transpile
4345
Promise<{
@@ -114,6 +116,7 @@ There is more behavior that you can define on a per-request basis that extends t
114116
- [`body`](#setting-the-body)
115117
- [`responseHandler`](#parsing-a-Response)
116118
- [`validateStatus`](#handling-non-standard-response-status-codes)
119+
- [`timeout`](#handling-a-custom-timeout)
117120

118121
```ts title="endpoint request options"
119122
interface FetchArgs extends RequestInit {
@@ -122,6 +125,7 @@ interface FetchArgs extends RequestInit {
122125
body?: any
123126
responseHandler?: 'json' | 'text' | ((response: Response) => Promise<any>)
124127
validateStatus?: (response: Response, body: any) => boolean
128+
timeout?: number
125129
}
126130

127131
const defaultValidateStatus = (response: Response) =>
@@ -227,3 +231,23 @@ export const customApi = createApi({
227231
}),
228232
})
229233
```
234+
235+
### Adding a custom timeout to requests
236+
237+
By default, `fetchBaseQuery` has no default timeout value set, meaning your requests will stay pending until your api resolves the request(s) or it reaches the browser's default timeout (normally 5 minutes). Most of the time, this isn't what you'll want. When using `fetchBaseQuery`, you have the ability to set a `timeout` on the `baseQuery` or on individual endpoints. When specifying both options, the endpoint value will take priority.
238+
239+
```ts title="Setting a timeout value"
240+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
241+
242+
export const api = createApi({
243+
baseQuery: fetchBaseQuery({ baseUrl: '/api/', timeout: 10000 }), // Set a default timeout of 10 seconds
244+
endpoints: (builder) => ({
245+
getUsers: builder.query({
246+
query: () => ({
247+
url: `users`,
248+
timeout: 1000, // We know the users endpoint is _really fast_ because it's always cached. We can assume if its over > 1000ms, something is wrong and we should abort the request.
249+
}),
250+
}),
251+
}),
252+
})
253+
```

packages/toolkit/src/query/fetchBaseQuery.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,9 @@ export type FetchBaseQueryMeta = { request: Request; response?: Response }
173173
*
174174
* @param {(params: Record<string, unknown>) => string} paramsSerializer
175175
* An optional function that can be used to stringify querystring parameters.
176+
*
177+
* @param {number} timeout
178+
* A number in milliseconds that represents that maximum time a request can take before timing out.
176179
*/
177180
export function fetchBaseQuery({
178181
baseUrl,

packages/toolkit/src/query/tests/fetchBaseQuery.test.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -723,8 +723,10 @@ describe('still throws on completely unexpected errors', () => {
723723
expect(req).toBeInstanceOf(Promise)
724724
await expect(req).rejects.toBe(error)
725725
})
726+
})
726727

727-
test('timeout behaviour', async () => {
728+
describe('timeout', () => {
729+
it('throws a timeout error when a request takes longer than specified timeout duration', async () => {
728730
jest.useFakeTimers()
729731
let result: any
730732
server.use(

0 commit comments

Comments
 (0)