Skip to content

Commit

Permalink
RFC: add "merge" functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
phryneas authored and markerikson committed May 30, 2022
1 parent aae9e53 commit 7225646
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
10 changes: 8 additions & 2 deletions packages/toolkit/src/query/core/buildSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { calculateProvidedByThunk } from './buildThunks'
import type {
AssertTagTypes,
EndpointDefinitions,
QueryDefinition,
} from '../endpointDefinitions'
import type { Patch } from 'immer'
import { applyPatches } from 'immer'
Expand Down Expand Up @@ -156,11 +157,16 @@ export function buildSlice({
meta.arg.queryCacheKey,
(substate) => {
if (substate.requestId !== meta.requestId) return
const { merge = (x: any) => x } = definitions[
meta.arg.endpointName
] as QueryDefinition<any, any, any, any>
substate.status = QueryStatus.fulfilled
let newData = merge(payload, substate.data)

substate.data =
definitions[meta.arg.endpointName].structuralSharing ?? true
? copyWithStructuralSharing(substate.data, payload)
: payload
? copyWithStructuralSharing(substate.data, newData)
: newData
delete substate.error
substate.fulfilledTimeStamp = meta.fulfilledTimeStamp
}
Expand Down
11 changes: 11 additions & 0 deletions packages/toolkit/src/query/endpointDefinitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,17 @@ export interface QueryExtraOptions<
* Not to be used. A query should not invalidate tags in the cache.
*/
invalidatesTags?: never
/**
* Can be provided to merge the current cache value into the new cache value.
*
* Useful if you don't want a new request to completely override the current cache value,
* maybe because you have manually updated it from another source and don't want those
* updates to get lost.
*/
merge?(
newCacheValue: ResultType,
currentCacheValue: ResultType | undefined
): ResultType
}

export type QueryDefinition<
Expand Down

0 comments on commit 7225646

Please sign in to comment.