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

Remove specific cache entry manually #4216

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 36 additions & 0 deletions docs/rtk-query/api/created-api/api-slice-utils.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,42 @@ dispatch(
patchCollection.undo()
```

### `removeQueryData`

#### Signature

```ts no-transpile
const removeQueryData = (
endpointName: string,
args: any
) => ThunkAction<void, PartialState, any, UnknownAction>;
```

- **Parameters**
- `endpointName`: a string matching an existing endpoint name
- `args`: a cache key, used to determine which cached dataset needs to be updated

#### Description

A Redux thunk that removes a specific query result from the cache. This immediately updates the Redux state with those changes.

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

#### Example

```ts no-transpile
const patchCollection = dispatch(
api.endpoints.getPosts.initiate(undefined),

// when cache data should be removed
dispatch(
api.util.removeQueryData(
'getPosts',
undefined,
),
)
```

### `prefetch`

#### Signature
Expand Down
25 changes: 25 additions & 0 deletions packages/toolkit/src/query/core/buildThunks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,14 @@ export type UpsertQueryDataThunk<
UnknownAction
>

export type RemoveQueryDataThunk<
Definitions extends EndpointDefinitions,
PartialState,
> = <EndpointName extends QueryKeys<Definitions>>(
endpointName: EndpointName,
args: QueryArgFrom<Definitions[EndpointName]>,
) => ThunkAction<void, PartialState, any, UnknownAction>

/**
* An object returned from dispatching a `api.util.updateQueryData` call.
*/
Expand Down Expand Up @@ -355,6 +363,22 @@ export function buildThunks<
)
}

const removeQueryData: RemoveQueryDataThunk<EndpointDefinitions, State> =
(endpointName, args) => (dispatch) => {
const endpointDefinition = endpointDefinitions[endpointName]

const queryCacheKey = serializeQueryArgs({
queryArgs: args,
endpointDefinition,
endpointName,
})


return dispatch(api.internalActions.removeQueryResult({
queryCacheKey
}))
}

const executeEndpoint: AsyncThunkPayloadCreator<
ThunkResult,
QueryThunkArg | MutationThunkArg,
Expand Down Expand Up @@ -670,6 +694,7 @@ In the case of an unhandled error, no tags will be "provided" or "invalidated".`
updateQueryData,
upsertQueryData,
patchQueryData,
removeQueryData,
buildMatchThunkActions,
}
}
Expand Down
19 changes: 19 additions & 0 deletions packages/toolkit/src/query/core/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
PatchQueryDataThunk,
UpdateQueryDataThunk,
UpsertQueryDataThunk,
RemoveQueryDataThunk,
} from './buildThunks'
import { buildThunks } from './buildThunks'
import type {
Expand Down Expand Up @@ -303,6 +304,22 @@ declare module '../apiTypes' {
RootState<Definitions, string, ReducerPath>
>

/**
* A Redux thunk that removes a specific query result from the cache. This immediately updates the Redux state with those changes.
*
* The thunk accepts two arguments: the name of the endpoint we are updating (such as `'getPost'`) and the appropriate query arg values to construct the desired cache key.
*
* @example
*
* ```ts
* dispatch(api.util.removeQueryData('getPost', { id: 1 }))
* ```
*/
removeQueryData: RemoveQueryDataThunk<
Definitions,
RootState<Definitions, string, ReducerPath>
>

/**
* A Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.
*
Expand Down Expand Up @@ -502,6 +519,7 @@ export const coreModule = ({
patchQueryData,
updateQueryData,
upsertQueryData,
removeQueryData,
prefetch,
buildMatchThunkActions,
} = buildThunks({
Expand Down Expand Up @@ -533,6 +551,7 @@ export const coreModule = ({
patchQueryData,
updateQueryData,
upsertQueryData,
removeQueryData,
prefetch,
resetApiState: sliceActions.resetApiState,
})
Expand Down
37 changes: 37 additions & 0 deletions packages/toolkit/src/query/tests/cacheCollection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,43 @@ describe(`query: await cleanup, keepUnusedDataFor set`, () => {
})
})

describe('removeCacheData', () => {
const { store, api } = storeForApi(
createApi({
baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
endpoints: (build) => ({
query: build.query<unknown, string>({
query: () => '/success',
}),
}),
}),
)

test('removeQueryData no impact if queryCacheKey different', async () => {
const promise = store.dispatch(api.endpoints.query.initiate('arg'))
await promise
const initialResponse = api.endpoints.query.select('arg')(store.getState())
expect(initialResponse.data).toBeDefined()

store.dispatch(api.util?.removeQueryData('query', 'argThatIsDifferent'))

const removedResult = api.endpoints.query.select('arg')(store.getState())
expect(removedResult.data).toBeDefined()
})

test('removeQueryData removes data of matching queryCacheKey', async () => {
const promise = store.dispatch(api.endpoints.query.initiate('arg'))
await promise
const initialResponse = api.endpoints.query.select('arg')(store.getState())
expect(initialResponse.data).toBeDefined()

store.dispatch(api.util?.removeQueryData('query', 'arg'))

const removedResult = api.endpoints.query.select('arg')(store.getState())
expect(removedResult.data).toBeUndefined()
})
})

function storeForApi<
A extends {
reducerPath: 'api'
Expand Down