Skip to content
Closed
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
1 change: 0 additions & 1 deletion docs/angular/guides/optimistic-updates.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ addTodo = injectMutation(() => ({

// access variables somewhere else

// Note: injectMutationState is not available yet in Angular Query
mutationState = injectMutationState<string>(() => ({
filters: { mutationKey: ['addTodo'], status: 'pending' },
select: (mutation) => mutation.state.variables,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { signal } from '@angular/core'
import { QueryClient } from '@tanstack/query-core'
import { TestBed } from '@angular/core/testing'
import { describe, expect, test, vi } from 'vitest'
import { injectMutation } from '../inject-mutation'
import { injectMutationState } from '../inject-mutation-state'
import { provideAngularQuery } from '../providers'
import { successMutator } from './test-utils'

describe('injectMutationState', () => {
let queryClient: QueryClient

beforeEach(() => {
queryClient = new QueryClient()
vi.useFakeTimers()
TestBed.configureTestingModule({
providers: [provideAngularQuery(queryClient)],
})
})

afterEach(() => {
vi.useRealTimers()
})

describe('injectMutationState', () => {
test('should return variables after calling mutate', async () => {
const mutationKey = ['mutation']
const variables = 'foo123'

const mutation = TestBed.runInInjectionContext(() => {
return injectMutation(() => ({
mutationKey: mutationKey,
mutationFn: (params: string) => successMutator(params),
}))
})

mutation.mutate(variables)

const mutationState = TestBed.runInInjectionContext(() => {
return injectMutationState(() => ({
filters: { mutationKey, status: 'pending' },
select: (m) => m.state.variables,
}))
})

expect(mutationState()).toEqual([variables])
})

test('reactive options should update injectMutationState', async () => {
const mutationKey1 = ['mutation1']
const mutationKey2 = ['mutation2']
const variables1 = 'foo123'
const variables2 = 'bar234'

const [mutation1, mutation2] = TestBed.runInInjectionContext(() => {
return [
injectMutation(() => ({
mutationKey: mutationKey1,
mutationFn: (params: string) => successMutator(params),
})),
injectMutation(() => ({
mutationKey: mutationKey2,
mutationFn: (params: string) => successMutator(params),
})),
]
})

mutation1.mutate(variables1)
mutation2.mutate(variables2)

const filterKey = signal(mutationKey1)

const mutationState = TestBed.runInInjectionContext(() => {
return injectMutationState(() => ({
filters: { mutationKey: filterKey(), status: 'pending' },
select: (m) => m.state.variables,
}))
})

expect(mutationState()).toEqual([variables1])

filterKey.set(mutationKey2)
TestBed.flushEffects()
expect(mutationState()).toEqual([variables2])
})

test('should return variables after calling mutate', async () => {
queryClient.clear()
const mutationKey = ['mutation']
const variables = 'bar234'

const mutation = TestBed.runInInjectionContext(() => {
return injectMutation(() => ({
mutationKey: mutationKey,
mutationFn: (params: string) => successMutator(params),
}))
})

mutation.mutate(variables)

const mutationState = TestBed.runInInjectionContext(() => {
return injectMutationState()
})

expect(mutationState()[0]?.variables).toEqual(variables)
})
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -121,27 +121,24 @@ describe('injectMutation', () => {

test('reactive options should update mutation', async () => {
const mutationCache = queryClient.getMutationCache()
const mutationKey = signal(['foo'])
// Signal will be updated before the mutation is called
// this test confirms that the mutation uses the updated value
const mutationKey = signal(['1'])
const mutation = TestBed.runInInjectionContext(() => {
return injectMutation(() => ({
mutationKey: mutationKey(),
mutationFn: (params: string) => successMutator(params),
}))
})

mutationKey.set(['bar'])

mutationKey.set(['2'])
TestBed.flushEffects()

await resolveMutations()

mutation.mutate('xyz')

await resolveMutations()

const mutations = mutationCache.find({ mutationKey: ['bar'] })
const mutations = mutationCache.find({ mutationKey: ['2'] })

expect(mutations?.options.mutationKey).toEqual(['bar'])
expect(mutations?.options.mutationKey).toEqual(['2'])
})

test('should reset state after invoking mutation.reset', async () => {
Expand Down
2 changes: 2 additions & 0 deletions packages/angular-query-experimental/src/create-base-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ export function createBaseQuery<
observer.setOptions(defaultedOptions, {
listeners: false,
})
// Setting the signal from an effect because it's both 'computed' from options()
// and needs to be set imperatively in the query observer listener.
resultSignal.set(observer.getOptimisticResult(defaultedOptions))
},
{ allowSignalWrites: true },
Expand Down
77 changes: 77 additions & 0 deletions packages/angular-query-experimental/src/inject-mutation-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { DestroyRef, effect, inject, signal } from '@angular/core'
import {
type DefaultError,
type Mutation,
type MutationCache,
type MutationFilters,
type MutationState,
notifyManager,
replaceEqualDeep,
} from '@tanstack/query-core'
import { assertInjector } from './util/assert-injector/assert-injector'
import { injectQueryClient } from './inject-query-client'
import type { Injector, Signal } from '@angular/core'

type MutationStateOptions<TResult = MutationState> = {
filters?: MutationFilters
select?: (
mutation: Mutation<unknown, DefaultError, unknown, unknown>,
) => TResult
}

function getResult<TResult = MutationState>(
mutationCache: MutationCache,
options: MutationStateOptions<TResult>,
): Array<TResult> {
return mutationCache
.findAll(options.filters)
.map(
(mutation): TResult =>
(options.select
? options.select(
mutation as Mutation<unknown, DefaultError, unknown, unknown>,
)
: mutation.state) as TResult,
)
}

export function injectMutationState<TResult = MutationState>(
options: () => MutationStateOptions<TResult> = () => ({}),
injector?: Injector,
): Signal<Array<TResult>> {
return assertInjector(injectMutationState, injector, () => {
const destroyRef = inject(DestroyRef)
const queryClient = injectQueryClient()

const mutationCache = queryClient.getMutationCache()

const result = signal<Array<TResult>>(getResult(mutationCache, options()))

effect(
() => {
// Setting the signal from an effect because it's both 'computed' from options()
// and needs to be set imperatively in the mutationCache listener.
result.set(getResult(mutationCache, options()))
},
{
allowSignalWrites: true,
},
Comment on lines +51 to +58
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
() => {
// Setting the signal from an effect because it's both 'computed' from options()
// and needs to be set imperatively in the mutationCache listener.
result.set(getResult(mutationCache, options()))
},
{
allowSignalWrites: true,
},
() => {
const options = options();
// Setting the signal from an effect because it's both 'computed' from options()
// and needs to be set imperatively in the mutationCache listener.
untracked(() => result.set(getResult(mutationCache, options)));
},

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Is the suggested change for this reason? https://twitter.com/GergelySzerovay/status/1754915190213144949

Copy link
Contributor

Choose a reason for hiding this comment

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

Yeah. More here: angular/angular#53986

)

const unsubscribe = mutationCache.subscribe(
notifyManager.batchCalls(() => {
const nextResult = replaceEqualDeep(
result(),
getResult(mutationCache, options()),
)
if (result() !== nextResult) {
result.set(nextResult)
}
}),
)

destroyRef.onDestroy(unsubscribe)

return result
})
}