Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fill out v1.9 remaining docs #2804

Merged
merged 10 commits into from
Oct 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
768 changes: 0 additions & 768 deletions .yarn/releases/yarn-3.1.0.cjs

This file was deleted.

801 changes: 801 additions & 0 deletions .yarn/releases/yarn-3.2.4.cjs

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions .yarnrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ nodeLinker: node-modules

plugins:
- path: .yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs
spec: "@yarnpkg/plugin-workspace-tools"
spec: '@yarnpkg/plugin-workspace-tools'
- path: .yarn/plugins/@yarnpkg/plugin-version.cjs
spec: "@yarnpkg/plugin-version"
spec: '@yarnpkg/plugin-version'

yarnPath: .yarn/releases/yarn-3.1.0.cjs
yarnPath: .yarn/releases/yarn-3.2.4.cjs
77 changes: 77 additions & 0 deletions docs/api/codemods.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
---
id: codemods
title: Codemods
sidebar_label: Codemods
hide_title: true
---

 

# Codemods

Per [the description in `1.9.0-alpha.0`](https://github.com/reduxjs/redux-toolkit/releases/tag/v1.9.0-alpha.0), we plan to remove the "object" argument from `createReducer` and `createSlice.extraReducers` in the future RTK 2.0 major version. In `1.9.0-alpha.0`, we added a one-shot runtime warning to each of those APIs.

To simplify upgrading codebases, we've published a set of codemods that will automatically transform the deprecated "object" syntax into the equivalent "builder" syntax.

The codemods package is available on NPM as [**`@reduxjs/rtk-codemods`**](https://www.npmjs.com/package/@reduxjs/rtk-codemods). It currently contains two codemods: `createReducerBuilder` and `createSliceBuilder`.

To run the codemods against your codebase, run `npx @reduxjs/rtk-codemods <TRANSFORM NAME> path/of/files/ or/some**/*glob.js`.

Examples:

```bash
npx @reduxjs/rtk-codemods createReducerBuilder ./src

npx @reduxjs/rtk-codemods createSliceBuilder ./packages/my-app/**/*.ts
```

We also recommend re-running Prettier on the codebase before committing the changes.

**These codemods _should_ work, but we would greatly appreciate testing and feedback on more real-world codebases!**

Before:

```js
createReducer(initialState, {
[todoAdded1a]: (state, action) => {
// stuff
},
[todoAdded1b]: (state, action) => action.payload,
})

const slice1 = createSlice({
name: 'a',
initialState: {},
extraReducers: {
[todoAdded1a]: (state, action) => {
// stuff
},
[todoAdded1b]: (state, action) => action.payload,
},
})
```

After:

```js
createReducer(initialState, (builder) => {
builder.addCase(todoAdded1a, (state, action) => {
// stuff
})

builder.addCase(todoAdded1b, (state, action) => action.payload)
})

const slice1 = createSlice({
name: 'a',
initialState: {},

extraReducers: (builder) => {
builder.addCase(todoAdded1a, (state, action) => {
// stuff
})

builder.addCase(todoAdded1b, (state, action) => action.payload)
},
})
```
2 changes: 1 addition & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"devDependencies": {
"@manaflair/redux-batch": "^1.0.0",
"@types/nanoid": "^2.1.0",
"@types/react": "^16.9.46",
"@types/react": "^18.0",
"@types/redux-logger": "^3.0.8",
"async-mutex": "^0.3.2",
"axios": "^0.20.0",
Expand Down
44 changes: 43 additions & 1 deletion docs/rtk-query/api/createApi.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,15 @@ If you specify `track: false` when manually dispatching queries, RTK Query will

_(required if no `queryFn` provided)_

```ts title="query signature" no-transpile
export type query = <QueryArg>(
arg: QueryArg
) => string | Record<string, unknown>

// with `fetchBaseQuery`
export type query = <QueryArg>(arg: QueryArg) => string | FetchArgs
```

[summary](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQuery.query)

[examples](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQuery.query)
Expand Down Expand Up @@ -490,12 +499,45 @@ See also [Invalidating cache data](../usage/automated-refetching.mdx#invalidatin

_(optional, only for query endpoints)_

Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only.
Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only.a

[summary](docblock://query/createApi.ts?token=CreateApiOptions.keepUnusedDataFor)

[examples](docblock://query/createApi.ts?token=CreateApiOptions.keepUnusedDataFor)

### `serializeQueryArgs`

_(optional, only for query endpoints)_

[summary](docblock://query/endpointDefinitions.ts?token=QueryExtraOptions.serializeQueryArgs)

[examples](docblock://query/endpointDefinitions.ts?token=QueryExtraOptions.serializeQueryArgs)

### `merge`

_(optional, only for query endpoints)_

[summary](docblock://query/endpointDefinitions.ts?token=QueryExtraOptions.merge)

[examples](docblock://query/endpointDefinitions.ts?token=QueryExtraOptions.merge)

### `forceRefetch`

_(optional, only for query endpoints)_

```ts title="forceRefetch signature" no-transpile
type forceRefetch = (params: {
currentArg: QueryArg | undefined
previousArg: QueryArg | undefined
state: RootState<any, any, string>
endpointState?: QuerySubState<any>
}) => boolean
```

[summary](docblock://query/endpointDefinitions.ts?token=QueryExtraOptions.forceRefetch)

[examples](docblock://query/endpointDefinitions.ts?token=QueryExtraOptions.forceRefetch)

### `onQueryStarted`

_(optional)_
Expand Down
52 changes: 47 additions & 5 deletions docs/rtk-query/api/created-api/api-slice-utils.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@ The API slice object includes various utilities that can be used for cache manag
such as implementing [optimistic updates](../../usage/manual-cache-updates.mdx#optimistic-updates),
as well implementing [server side rendering](../../usage/server-side-rendering.mdx).

These are included in a `util` field inside the slice object.
These are included as `api.util` inside the API object.

:::info

Some of the TS types on this page are pseudocode to illustrate intent, as the actual internal types are fairly complex.

:::

### `updateQueryData`

Expand Down Expand Up @@ -48,8 +54,7 @@ The thunk returns an object containing `{patches: Patch[], inversePatches: Patch

This is typically used as the first step in implementing optimistic updates. The generated `inversePatches` can be used to revert the updates by calling `dispatch(patchQueryData(endpointName, args, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.

Note that the first two arguments (`endpointName` and `args`) are used to determine which existing
cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.
Note that the first two arguments (`endpointName` and `args`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.

#### Example 1

Expand Down Expand Up @@ -105,6 +110,43 @@ dispatch(api.endpoints.getPostById.initiate(1))
dispatch(api.endpoints.getPostById.initiate(1, { ...options }))
```

### `upsertQueryData`

#### Signature

```ts no-transpile
const upsertQueryData = <T>(
endpointName: string,
args: any,
newEntryData: T
) => ThunkAction<Promise<CacheEntry<T>>, PartialState, any, AnyAction>;
```

- **Parameters**
- `endpointName`: a string matching an existing endpoint name
- `args`: an argument matching that used for a previous query call, used to determine which cached dataset needs to be updated
- `newEntryValue`: the value to be written into the corresponding cache entry's `data` field

#### Description

A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.

The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and the data to upsert.

If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the value being upserted is undefined, will it remove the cache key entirely? If not, is there a way to remove a cache entry entirely? (ie, like invalidateTags, but without triggering a refetch)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ggaabe : no, it would replace the .data field with undefined. It's the value, not the key.

There isn't currently a way to remove one, but a few folks have asked for something like this. Could you comment over in #2820 and describe when and why you might want to do that?


The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.

If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a "last result wins" update behavior.

#### Example

```ts no-transpile
await dispatch(
api.util.upsertQueryData('getPost', { id: 1 }, { id: 1, text: 'Hello!' })
)
```

### `patchQueryData`

#### Signature
Expand All @@ -124,9 +166,9 @@ const patchQueryData = (

#### Description

A Redux thunk action creator that applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.
A Redux thunk action creator that, when dispatched, applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.

The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), any relevant query arguments, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.
The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.

This is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching `patchQueryData` with the `inversePatches` that were generated by `updateQueryData` earlier.

Expand Down
Loading