Skip to content

Commit 7225646

Browse files
phryneasmarkerikson
authored andcommitted
RFC: add "merge" functionality
1 parent aae9e53 commit 7225646

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

packages/toolkit/src/query/core/buildSlice.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { calculateProvidedByThunk } from './buildThunks'
2727
import type {
2828
AssertTagTypes,
2929
EndpointDefinitions,
30+
QueryDefinition,
3031
} from '../endpointDefinitions'
3132
import type { Patch } from 'immer'
3233
import { applyPatches } from 'immer'
@@ -156,11 +157,16 @@ export function buildSlice({
156157
meta.arg.queryCacheKey,
157158
(substate) => {
158159
if (substate.requestId !== meta.requestId) return
160+
const { merge = (x: any) => x } = definitions[
161+
meta.arg.endpointName
162+
] as QueryDefinition<any, any, any, any>
159163
substate.status = QueryStatus.fulfilled
164+
let newData = merge(payload, substate.data)
165+
160166
substate.data =
161167
definitions[meta.arg.endpointName].structuralSharing ?? true
162-
? copyWithStructuralSharing(substate.data, payload)
163-
: payload
168+
? copyWithStructuralSharing(substate.data, newData)
169+
: newData
164170
delete substate.error
165171
substate.fulfilledTimeStamp = meta.fulfilledTimeStamp
166172
}

packages/toolkit/src/query/endpointDefinitions.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,17 @@ export interface QueryExtraOptions<
272272
* Not to be used. A query should not invalidate tags in the cache.
273273
*/
274274
invalidatesTags?: never
275+
/**
276+
* Can be provided to merge the current cache value into the new cache value.
277+
*
278+
* Useful if you don't want a new request to completely override the current cache value,
279+
* maybe because you have manually updated it from another source and don't want those
280+
* updates to get lost.
281+
*/
282+
merge?(
283+
newCacheValue: ResultType,
284+
currentCacheValue: ResultType | undefined
285+
): ResultType
275286
}
276287

277288
export type QueryDefinition<

0 commit comments

Comments
 (0)