Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
RFC: add "merge" functionality
  • Loading branch information
phryneas authored and markerikson committed Aug 13, 2022
commit 4860a8909315a7ca311583b4a0691c8756d9749c
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
12 changes: 12 additions & 0 deletions packages/toolkit/src/query/endpointDefinitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,18 @@ export interface QueryExtraOptions<
invalidatesTags?: never

serializeQueryArgs?: SerializeQueryArgs<any>

/**
* 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