Skip to content

Commit ebe1777

Browse files
authoredApr 18, 2023
Merge pull request #3311 from EskiMojo14/remark-typescript-update
2 parents eb586b6 + d746bee commit ebe1777

17 files changed

+83
-76
lines changed
 

‎docs/rtk-query/api/created-api/endpoints.mdx

+8-7
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ When dispatching an action creator, you're responsible for storing a reference t
9292

9393
#### Example
9494

95-
```tsx title="initiate query example"
95+
```tsx no-transpile title="initiate query example"
9696
import { useState } from 'react'
9797
import { useAppDispatch } from './store/hooks'
9898
import { api } from './services/api'
@@ -119,7 +119,7 @@ function App() {
119119
}
120120
```
121121

122-
```tsx title="initiate mutation example"
122+
```tsx no-transpile title="initiate mutation example"
123123
import { useState } from 'react'
124124
import { useAppDispatch } from './store/hooks'
125125
import { api, Post } from './services/api'
@@ -187,7 +187,7 @@ Each call to `.select(someCacheKey)` returns a _new_ selector function instance.
187187
188188
#### Example
189189
190-
```tsx title="select query example"
190+
```tsx no-transpile title="select query example"
191191
import { useState, useMemo } from 'react'
192192
import { useAppDispatch, useAppSelector } from './store/hooks'
193193
import { api } from './services/api'
@@ -198,9 +198,10 @@ function App() {
198198
// highlight-start
199199
// useMemo is used to only call `.select()` when required.
200200
// Each call will create a new selector function instance
201-
const selectPost = useMemo(() => api.endpoints.getPost.select(postId), [
202-
postId,
203-
])
201+
const selectPost = useMemo(
202+
() => api.endpoints.getPost.select(postId),
203+
[postId]
204+
)
204205
const { data, isLoading } = useAppSelector(selectPost)
205206
// highlight-end
206207

@@ -223,7 +224,7 @@ function App() {
223224
}
224225
```
225226

226-
```tsx title="select mutation example"
227+
```tsx no-transpile title="select mutation example"
227228
import { useState, useMemo } from 'react'
228229
import { skipToken } from '@reduxjs/toolkit/query'
229230
import { useAppDispatch, useAppSelector } from './store/hooks'

‎docs/rtk-query/usage-with-typescript.mdx

+8-9
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,7 @@ export const api = createApi({
467467
export const { useGetPostQuery } = api
468468
```
469469
470-
```tsx title="Using skip in a component"
470+
```tsx no-transpile title="Using skip in a component"
471471
import { useGetPostQuery } from './api'
472472
473473
function MaybePost({ id }: { id?: number }) {
@@ -486,7 +486,7 @@ While you might be able to convince yourself that the query won't be called unle
486486

487487
RTK Query provides a `skipToken` export which can be used as an alternative to the `skip` option in order to skip queries, while remaining type-safe. When `skipToken` is passed as the query argument to `useQuery`, `useQueryState` or `useQuerySubscription`, it provides the same effect as setting `skip: true` in the query options, while also being a valid argument in scenarios where the `arg` might be undefined otherwise.
488488

489-
```tsx title="Using skipToken in a component"
489+
```tsx no-transpile title="Using skipToken in a component"
490490
import { skipToken } from '@reduxjs/toolkit/query/react'
491491
import { useGetPostQuery } from './api'
492492

@@ -566,7 +566,7 @@ export interface SerializedError {
566566
When using `fetchBaseQuery`, the `error` property returned from a hook will have the type `FetchBaseQueryError | SerializedError | undefined`.
567567
If an error is present, you can access error properties after narrowing the type to either `FetchBaseQueryError` or `SerializedError`.
568568

569-
```tsx
569+
```tsx no-transpile
570570
import { api } from './services/api'
571571

572572
function PostDetail() {
@@ -587,10 +587,9 @@ function PostDetail() {
587587
<div>{errMsg}</div>
588588
</div>
589589
)
590-
}
591-
else {
592-
// you can access all properties of `SerializedError` here
593-
return <div>{error.message}</div>
590+
} else {
591+
// you can access all properties of `SerializedError` here
592+
return <div>{error.message}</div>
594593
}
595594
}
596595

@@ -617,7 +616,7 @@ In order to safely access properties of the error, you must first narrow the typ
617616
This can be done using a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)
618617
as shown below.
619618

620-
```tsx title="services/helpers.ts"
619+
```tsx no-transpile title="services/helpers.ts"
621620
import { FetchBaseQueryError } from '@reduxjs/toolkit/query'
622621

623622
/**
@@ -644,7 +643,7 @@ export function isErrorWithMessage(
644643
}
645644
```
646645

647-
```tsx title="addPost.tsx"
646+
```tsx no-transpile title="addPost.tsx"
648647
import { useState } from 'react'
649648
import { useSnackbar } from 'notistack'
650649
import { api } from './services/api'

‎docs/rtk-query/usage/automated-refetching.mdx

+2-2
Original file line numberDiff line numberDiff line change
@@ -668,7 +668,7 @@ export const api = createApi({
668668
export const { useGetPostsQuery, useGetPostQuery, useAddPostMutation } = api
669669
```
670670

671-
```tsx title="App.tsx"
671+
```tsx no-transpile title="App.tsx"
672672
function App() {
673673
const { data: posts } = useGetPostsQuery()
674674
const [addPost] = useAddPostMutation()
@@ -742,7 +742,7 @@ export const api = createApi({
742742
export const { useGetPostsQuery, useAddPostMutation, useGetPostQuery } = api
743743
```
744744

745-
```tsx title="App.tsx"
745+
```tsx no-transpile title="App.tsx"
746746
function App() {
747747
const { data: posts } = useGetPostsQuery()
748748
const [addPost] = useAddPostMutation()

‎docs/rtk-query/usage/cache-behavior.mdx

+2-2
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ Calling the `refetch` function will force refetch the associated query.
120120

121121
Alternatively, you can dispatch the `initiate` thunk action for an endpoint, passing the option `forceRefetch: true` to the thunk action creator for the same effect.
122122

123-
```tsx title="Force refetch example"
123+
```tsx no-transpile title="Force refetch example"
124124
import { useDispatch } from 'react-redux'
125125
import { useGetPostsQuery } from './api'
126126

@@ -197,7 +197,7 @@ export const api = createApi({
197197
})
198198
```
199199

200-
```tsx title="Forcing refetch on component mount"
200+
```tsx no-transpile title="Forcing refetch on component mount"
201201
import { useGetPostsQuery } from './api'
202202

203203
const Component = () => {

‎docs/rtk-query/usage/error-handling.mdx

+12-13
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ If your query or mutation happens to throw an error when using [fetchBaseQuery](
1616

1717
### Error Display Examples
1818

19-
```tsx title="Query Error"
19+
```tsx no-transpile title="Query Error"
2020
function PostsList() {
2121
const { data, error } = useGetPostsQuery()
2222

@@ -28,7 +28,7 @@ function PostsList() {
2828
}
2929
```
3030

31-
```tsx title="Mutation Error"
31+
```tsx no-transpile title="Mutation Error"
3232
function AddPost() {
3333
const [addPost, { error }] = useAddPostMutation()
3434

@@ -52,7 +52,7 @@ addPost({ id: 1, name: 'Example' })
5252

5353
:::
5454

55-
```tsx title="Manually selecting an error"
55+
```tsx no-transpile title="Manually selecting an error"
5656
function PostsList() {
5757
const { error } = useSelector(api.endpoints.getPosts.select())
5858

@@ -88,15 +88,14 @@ import { toast } from 'your-cool-library'
8888
/**
8989
* Log a warning and show a toast!
9090
*/
91-
export const rtkQueryErrorLogger: Middleware = (api: MiddlewareAPI) => (
92-
next
93-
) => (action) => {
94-
// RTK Query uses `createAsyncThunk` from redux-toolkit under the hood, so we're able to utilize these matchers!
95-
if (isRejectedWithValue(action)) {
96-
console.warn('We got a rejected action!')
97-
toast.warn({ title: 'Async error!', message: action.error.data.message })
91+
export const rtkQueryErrorLogger: Middleware =
92+
(api: MiddlewareAPI) => (next) => (action) => {
93+
// RTK Query uses `createAsyncThunk` from redux-toolkit under the hood, so we're able to utilize these matchers!
94+
if (isRejectedWithValue(action)) {
95+
console.warn('We got a rejected action!')
96+
toast.warn({ title: 'Async error!', message: action.error.data.message })
97+
}
98+
99+
return next(action)
98100
}
99-
100-
return next(action)
101-
}
102101
```

‎docs/rtk-query/usage/manual-cache-updates.mdx

+1-1
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ callback for a mutation without a good reason, as RTK Query is intended to be us
217217
your cached data as a reflection of the server-side state.
218218
:::
219219

220-
```tsx title="General manual cache update example"
220+
```tsx no-transpile title="General manual cache update example"
221221
import { api } from './api'
222222
import { useAppDispatch } from './store/hooks'
223223

‎docs/rtk-query/usage/migrating-to-rtk-query.mdx

+4-4
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ export type RootState = ReturnType<typeof store.getState>
169169
170170
In order to have the store accessible within our app, we will wrap our `App` component with a [`Provider`](https://react-redux.js.org/api/provider) component from `react-redux`.
171171
172-
```tsx title="src/index.ts"
172+
```tsx no-transpile title="src/index.ts"
173173
import { render } from 'react-dom'
174174
// highlight-start
175175
import { Provider } from 'react-redux'
@@ -223,9 +223,9 @@ export type RootState = {
223223
pokemon: typeof initialPokemonSlice
224224
}
225225

226-
export declare const store: EnhancedStore<RootState>
226+
export declare const store: EnhancedStore<RootState>
227227
export type AppDispatch = typeof store.dispatch
228-
export declare const useAppDispatch: () => (...args: any[])=> any;
228+
export declare const useAppDispatch: () => (...args: any[]) => any
229229

230230
// file: src/hooks.ts
231231
import { useEffect } from 'react'
@@ -276,7 +276,7 @@ Our implementation below provides the following behaviour in the component:
276276
- When our component is mounted, if a request for the provided pokemon name has not already been sent for the session, send the request off
277277
- The hook always provides the latest received `data` when available, as well as the request status booleans `isUninitialized`, `isPending`, `isFulfilled` & `isRejected` in order to determine the current UI at any given moment as a function of our state.
278278

279-
```tsx title="src/App.tsx"
279+
```tsx no-transpile title="src/App.tsx"
280280
import * as React from 'react'
281281
// highlight-start
282282
import { useGetPokemonByNameQuery } from './hooks'

‎docs/rtk-query/usage/mutations.mdx

+6-2
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,11 @@ const api = createApi({
5252
// Pick out data and prevent nested properties in a hook or selector
5353
transformResponse: (response: { data: Post }, meta, arg) => response.data,
5454
// Pick out errors and prevent nested properties in a hook or selector
55-
transformErrorResponse: (response: { status: string | number }, meta, arg) => response.status,
55+
transformErrorResponse: (
56+
response: { status: string | number },
57+
meta,
58+
arg
59+
) => response.status,
5660
invalidatesTags: ['Post'],
5761
// onQueryStarted is useful for optimistic updates
5862
// The 2nd parameter is the destructured `MutationLifecycleApi`
@@ -177,7 +181,7 @@ When using `fixedCacheKey`, the `originalArgs` property is not able to be shared
177181

178182
This is a modified version of the complete example you can see at the bottom of the page to highlight the `updatePost` mutation. In this scenario, a post is fetched with `useQuery`, and then an `EditablePostName` component is rendered that allows us to edit the name of the post.
179183

180-
```tsx title="src/features/posts/PostDetail.tsx"
184+
```tsx no-transpile title="src/features/posts/PostDetail.tsx"
181185
export const PostDetail = () => {
182186
const { id } = useParams<{ id: any }>()
183187

‎docs/rtk-query/usage/pagination.mdx

+19-19
Original file line numberDiff line numberDiff line change
@@ -44,36 +44,35 @@ export const { useListPostsQuery } = api
4444

4545
### Trigger the next page by incrementing the `page` state variable
4646

47-
```tsx title="src/features/posts/PostsManager.tsx"
47+
```tsx no-transpile title="src/features/posts/PostsManager.tsx"
4848
const PostList = () => {
49-
const [page, setPage] = useState(1);
50-
const { data: posts, isLoading, isFetching } = useListPostsQuery(page);
49+
const [page, setPage] = useState(1)
50+
const { data: posts, isLoading, isFetching } = useListPostsQuery(page)
5151

5252
if (isLoading) {
53-
return <div>Loading</div>;
53+
return <div>Loading</div>
5454
}
5555

5656
if (!posts?.data) {
57-
return <div>No posts :(</div>;
57+
return <div>No posts :(</div>
5858
}
5959

6060
return (
6161
<div>
62-
{posts.data.map(({ id, title, status }) => (
63-
<div key={id}>{title} - {status}</div>
64-
))}
65-
<button onClick={() => setPage(page - 1)} isLoading={isFetching}>
66-
Previous
67-
</button>
68-
<button
69-
onClick={() => setPage(page + 1)}
70-
isLoading={isFetching}
71-
>
72-
Next
73-
</button>
62+
{posts.data.map(({ id, title, status }) => (
63+
<div key={id}>
64+
{title} - {status}
65+
</div>
66+
))}
67+
<button onClick={() => setPage(page - 1)} isLoading={isFetching}>
68+
Previous
69+
</button>
70+
<button onClick={() => setPage(page + 1)} isLoading={isFetching}>
71+
Next
72+
</button>
7473
</div>
75-
);
76-
};
74+
)
75+
}
7776
```
7877

7978
### Automated Re-fetching of Paginated Queries
@@ -149,6 +148,7 @@ export const postApi = createApi({
149148
}),
150149
})
151150
```
151+
152152
## General Pagination Example
153153

154154
In the following example, you'll see `Loading` on the initial query, but then as you move forward we'll use the next/previous buttons as a _fetching_ indicator while any non-cached query is performed. When you go back, the cached data will be served instantaneously.

‎docs/rtk-query/usage/polling.mdx

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ description: 'RTK Query > Usage > Polling: re-fetching data on a timer'
1414

1515
Polling gives you the ability to have a 'real-time' effect by causing a query to run at a specified interval. To enable polling for a query, pass a `pollingInterval` to the `useQuery` hook or action creator with an interval in milliseconds:
1616

17-
```tsx title="src/Pokemon.tsx" no-transpile
17+
```tsx no-transpile title="src/Pokemon.tsx" no-transpile
1818
import * as React from 'react'
1919
import { useGetPokemonByNameQuery } from './services/pokemon'
2020

‎docs/rtk-query/usage/prefetching.mdx

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ You can specify these prefetch options when declaring the hook or at the call si
5858
- **Assuming** you have a `useQuery` hook in the tree that is subscribed to the same query that you are prefetching:
5959
- `useQuery` will return `{isLoading: false, isFetching: true, ...rest`}
6060

61-
```tsx title="usePrefetch Example"
61+
```tsx no-transpile title="usePrefetch Example"
6262
function User() {
6363
const prefetchUser = usePrefetch('getUser')
6464

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

+10-6
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,11 @@ const api = createApi({
5959
// Pick out data and prevent nested properties in a hook or selector
6060
transformResponse: (response: { data: Post }, meta, arg) => response.data,
6161
// Pick out errors and prevent nested properties in a hook or selector
62-
transformErrorResponse: (response: { status: string | number }, meta, arg) => response.status,
62+
transformErrorResponse: (
63+
response: { status: string | number },
64+
meta,
65+
arg
66+
) => response.status,
6367
providesTags: (result, error, id) => [{ type: 'Post', id }],
6468
// The 2nd parameter is the destructured `QueryLifecycleApi`
6569
async onQueryStarted(
@@ -158,7 +162,7 @@ In most cases, you will probably read `data` and either `isLoading` or `isFetchi
158162

159163
Here is an example of a `PostDetail` component:
160164

161-
```tsx title="Example"
165+
```tsx no-transpile title="Example"
162166
export const PostDetail = ({ id }: { id: string }) => {
163167
const {
164168
data: post,
@@ -199,7 +203,7 @@ For query endpoints, RTK Query maintains a semantic distinction between `isLoadi
199203

200204
This distinction allows for greater control when handling UI behavior. For example, `isLoading` can be used to display a skeleton while loading for the first time, while `isFetching` can be used to grey out old data when changing from page 1 to page 2 or when data is invalidated and re-fetched.
201205

202-
```tsx title="Managing UI behavior with Query Loading States"
206+
```tsx no-transpile title="Managing UI behavior with Query Loading States"
203207
import { Skeleton } from './Skeleton'
204208
import { useGetPostsQuery } from './api'
205209

@@ -236,7 +240,7 @@ shown. If posts for the current user have previously been fetched, and are re-fe
236240
result of a mutation), the UI will show the previous data, but will grey out the data. If the user
237241
changes, it will instead show the skeleton again as opposed to greying out data for the previous user.
238242

239-
```tsx title="Managing UI behavior with currentData"
243+
```tsx no-transpile title="Managing UI behavior with currentData"
240244
import { Skeleton } from './Skeleton'
241245
import { useGetPostsByUserQuery } from './api'
242246

@@ -274,7 +278,7 @@ Sometimes you may have a parent component that is subscribed to a query, and the
274278

275279
`selectFromResult` allows you to get a specific segment from a query result in a performant manner. When using this feature, the component will not rerender unless the underlying data of the selected item has changed. If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
276280

277-
```tsx title="Using selectFromResult to extract a single result"
281+
```tsx no-transpile title="Using selectFromResult to extract a single result"
278282
function PostsList() {
279283
const { data: posts } = api.useGetPostsQuery()
280284

@@ -301,7 +305,7 @@ function PostById({ id }: { id: number }) {
301305

302306
Note that a shallow equality check is performed on the overall return value of `selectFromResult` to determine whether to force a rerender. i.e. it will trigger a rerender if any of the returned object values change reference. If a new array/object is created and used as a return value within the callback, it will hinder the performance benefits due to being identified as a new item each time the callback is run. When intentionally providing an empty array/object, in order to avoid re-creating it each time the callback runs, you can declare an empty array/object outside of the component in order to maintain a stable reference.
303307

304-
```tsx title="Using selectFromResult with a stable empty array"
308+
```tsx no-transpile title="Using selectFromResult with a stable empty array"
305309
// An array declared here will maintain a stable reference rather than be re-created again
306310
const emptyArray: Post[] = []
307311

0 commit comments

Comments
 (0)
Please sign in to comment.