Skip to content

Commit bdc4e3f

Browse files
authored
Merge pull request #1115 from Shrugsy/docs/dynamic-base-url-example-snippet
📝 Add dynamic base url example snippet
2 parents 0075ca9 + 1eea9e9 commit bdc4e3f

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

docs/rtk-query/usage/customizing-queries.mdx

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,7 @@ import {
343343
FetchBaseQueryError,
344344
} from '@reduxjs/toolkit/query'
345345
import { tokenReceived, loggedOut } from './authSlice'
346+
346347
const baseQuery = fetchBaseQuery({ baseUrl: '/' })
347348
const baseQueryWithReauth: BaseQueryFn<
348349
string | FetchArgs,
@@ -530,6 +531,86 @@ const api = createApi({
530531
})
531532
```
532533
534+
### Constructing a Dynamic Base URL using Redux state
535+
536+
In some cases, you may wish to have a dynamically altered base url determined from a property in your Redux state. A `baseQuery` has access to a [`getState`](../api/createApi.mdx#basequery-function-arguments) method that provides the current store state at the time it is called. This can be used to construct the desired url using a partial url string, and the appropriate data from your store state.
537+
538+
```ts title="Dynamically generated Base URL example"
539+
// file: src/store.ts noEmit
540+
export type RootState = {
541+
auth: {
542+
projectId: number | null
543+
}
544+
}
545+
546+
// file: src/services/projectSlice.ts noEmit
547+
import type { RootState } from '../store'
548+
export const selectProjectId = (state: RootState) => state.auth.projectId
549+
550+
// file: src/services/types.ts noEmit
551+
export interface Post {
552+
id: number
553+
name: string
554+
}
555+
556+
// file: src/services/api.ts
557+
import {
558+
createApi,
559+
BaseQueryFn,
560+
FetchArgs,
561+
fetchBaseQuery,
562+
FetchBaseQueryError,
563+
} from '@reduxjs/toolkit/query/react'
564+
import type { Post } from './types'
565+
import { selectProjectId } from './projectSlice'
566+
import type { RootState } from '../store'
567+
568+
const rawBaseQuery = fetchBaseQuery({
569+
baseUrl: 'www.my-cool-site.com/',
570+
})
571+
572+
const dynamicBaseQuery: BaseQueryFn<
573+
string | FetchArgs,
574+
unknown,
575+
FetchBaseQueryError
576+
> = async (args, api, extraOptions) => {
577+
const projectId = selectProjectId(api.getState() as RootState)
578+
// gracefully handle scenarios where data to generate the URL is missing
579+
if (!projectId) {
580+
return {
581+
error: {
582+
status: 400,
583+
data: 'No project ID received',
584+
},
585+
}
586+
}
587+
588+
const urlEnd = typeof args === 'string' ? args : args.url
589+
// construct a dynamically generated portion of the url
590+
const adjustedUrl = `project/${projectId}/${urlEnd}`
591+
const adjustedArgs =
592+
typeof args === 'string' ? adjustedUrl : { ...args, url: adjustedUrl }
593+
// provide the amended url and other params to the raw base query
594+
return rawBaseQuery(adjustedArgs, api, extraOptions)
595+
}
596+
597+
export const api = createApi({
598+
baseQuery: dynamicBaseQuery,
599+
endpoints: (builder) => ({
600+
getPosts: builder.query<Post[], void>({
601+
query: () => 'posts',
602+
}),
603+
}),
604+
})
605+
606+
export const { useGetPostsQuery } = api
607+
608+
/*
609+
Using `useGetPostsQuery()` where a `projectId` of 500 is in the redux state will result in
610+
a request being sent to www.my-cool-site.com/project/500/posts
611+
*/
612+
```
613+
533614
## Examples - `transformResponse`
534615

535616
### Unpacking deeply nested GraphQL data

0 commit comments

Comments
 (0)