Skip to content

Commit

Permalink
fix(angular-query): remove queryClient parameter from callback functi…
Browse files Browse the repository at this point in the history
…ons (#8307)
  • Loading branch information
arnoud-dv authored Nov 19, 2024
1 parent fa77f32 commit 4aff846
Show file tree
Hide file tree
Showing 8 changed files with 46 additions and 71 deletions.
6 changes: 3 additions & 3 deletions docs/framework/angular/guides/invalidations-from-mutations.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ export class TodosComponent {
queryClient = inject(QueryClient)

// When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key
mutation = injectMutation((client) => ({
mutation = injectMutation(() => ({
mutationFn: addTodo,
onSuccess: () => {
client.invalidateQueries({ queryKey: ['todos'] })
client.invalidateQueries({ queryKey: ['reminders'] })
this.queryClient.invalidateQueries({ queryKey: ['todos'] })
this.queryClient.invalidateQueries({ queryKey: ['reminders'] })

// OR use the queryClient that is injected into the component
// this.queryClient.invalidateQueries({ queryKey: ['todos'] })
Expand Down
27 changes: 17 additions & 10 deletions docs/framework/angular/guides/optimistic-updates.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,19 +82,21 @@ mutationState = injectMutationState<string>(() => ({
[//]: # 'Example'

```ts
updateTodo = injectMutation((client) => ({
queryClient = inject(QueryClient)

updateTodo = injectMutation(() => ({
mutationFn: updateTodo,
// When mutate is called:
onMutate: async (newTodo) => {
// Cancel any outgoing refetches
// (so they don't overwrite our optimistic update)
await client.cancelQueries({ queryKey: ['todos'] })
await this.queryClient.cancelQueries({ queryKey: ['todos'] })

// Snapshot the previous value
const previousTodos = client.getQueryData(['todos'])

// Optimistically update to the new value
client.setQueryData(['todos'], (old) => [...old, newTodo])
this.queryClient.setQueryData(['todos'], (old) => [...old, newTodo])

// Return a context object with the snapshotted value
return { previousTodos }
Expand All @@ -106,7 +108,7 @@ updateTodo = injectMutation((client) => ({
},
// Always refetch after error or success:
onSettled: () => {
client.invalidateQueries({ queryKey: ['todos'] })
this.queryClient.invalidateQueries({ queryKey: ['todos'] })
},
}))
```
Expand All @@ -115,30 +117,35 @@ updateTodo = injectMutation((client) => ({
[//]: # 'Example2'

```ts
updateTodo = injectMutation((client) => ({
queryClient = inject(QueryClient)

updateTodo = injectMutation(() => ({
mutationFn: updateTodo,
// When mutate is called:
onMutate: async (newTodo) => {
// Cancel any outgoing refetches
// (so they don't overwrite our optimistic update)
await client.cancelQueries({ queryKey: ['todos', newTodo.id] })
await this.queryClient.cancelQueries({ queryKey: ['todos', newTodo.id] })

// Snapshot the previous value
const previousTodo = client.getQueryData(['todos', newTodo.id])
const previousTodo = this.queryClient.getQueryData(['todos', newTodo.id])

// Optimistically update to the new value
client.setQueryData(['todos', newTodo.id], newTodo)
this.queryClient.setQueryData(['todos', newTodo.id], newTodo)

// Return a context with the previous and new todo
return { previousTodo, newTodo }
},
// If the mutation fails, use the context we returned above
onError: (err, newTodo, context) => {
client.setQueryData(['todos', context.newTodo.id], context.previousTodo)
this.queryClient.setQueryData(
['todos', context.newTodo.id],
context.previousTodo,
)
},
// Always refetch after error or success:
onSettled: (newTodo) => {
client.invalidateQueries({ queryKey: ['todos', newTodo.id] })
this.queryClient.invalidateQueries({ queryKey: ['todos', newTodo.id] })
},
}))
```
Expand Down
8 changes: 2 additions & 6 deletions docs/framework/angular/quick-start.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,10 @@ export class TodosComponent {
queryFn: () => this.todoService.getTodos(),
}))
mutation = injectMutation((client) => ({
mutation = injectMutation(() => ({
mutationFn: (todo: Todo) => this.todoService.addTodo(todo),
onSuccess: () => {
// Invalidate and refetch by using the client directly
client.invalidateQueries({ queryKey: ['todos'] })
// OR use the queryClient that is injected into the component
// this.queryClient.invalidateQueries({ queryKey: ['todos'] })
this.queryClient.invalidateQueries({ queryKey: ['todos'] })
},
}))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,23 +36,6 @@ describe('injectMutation', () => {
vi.useRealTimers()
})

describe('callback helpers', () => {
test('can access client from options callback', async () => {
const mutation = TestBed.runInInjectionContext(() => {
return injectMutation((client) => ({
mutationFn: () => {
expect(client).toBe(queryClient)
return Promise.resolve()
},
}))
})

mutation.mutate()
vi.advanceTimersByTime(1)
expect(mutation.status()).toBe('pending')
})
})

test('should be in idle state initially', () => {
const mutation = TestBed.runInInjectionContext(() => {
return injectMutation(() => ({
Expand Down
8 changes: 2 additions & 6 deletions packages/angular-query-experimental/src/create-base-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@ export function createBaseQuery<
TQueryData,
TQueryKey extends QueryKey,
>(
optionsFn: (
client: QueryClient,
) => CreateBaseQueryOptions<
optionsFn: () => CreateBaseQueryOptions<
TQueryFnData,
TError,
TData,
Expand All @@ -54,9 +52,7 @@ export function createBaseQuery<
* are preserved and can keep being applied after signal changes
*/
const defaultedOptionsSignal = computed(() => {
const options = runInInjectionContext(injector, () =>
optionsFn(queryClient),
)
const options = runInInjectionContext(injector, () => optionsFn())
const defaultedOptions = queryClient.defaultQueryOptions(options)
defaultedOptions._optimisticResults = 'optimistic'
return defaultedOptions
Expand Down
15 changes: 4 additions & 11 deletions packages/angular-query-experimental/src/inject-infinite-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import type { Injector } from '@angular/core'
import type {
DefaultError,
InfiniteData,
QueryClient,
QueryKey,
QueryObserver,
} from '@tanstack/query-core'
Expand Down Expand Up @@ -34,9 +33,7 @@ export function injectInfiniteQuery<
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
optionsFn: (
client: QueryClient,
) => DefinedInitialDataInfiniteOptions<
optionsFn: () => DefinedInitialDataInfiniteOptions<
TQueryFnData,
TError,
TData,
Expand All @@ -61,9 +58,7 @@ export function injectInfiniteQuery<
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
optionsFn: (
client: QueryClient,
) => UndefinedInitialDataInfiniteOptions<
optionsFn: () => UndefinedInitialDataInfiniteOptions<
TQueryFnData,
TError,
TData,
Expand All @@ -88,9 +83,7 @@ export function injectInfiniteQuery<
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
optionsFn: (
client: QueryClient,
) => CreateInfiniteQueryOptions<
optionsFn: () => CreateInfiniteQueryOptions<
TQueryFnData,
TError,
TData,
Expand All @@ -110,7 +103,7 @@ export function injectInfiniteQuery<
* @public
*/
export function injectInfiniteQuery(
optionsFn: (client: QueryClient) => CreateInfiniteQueryOptions,
optionsFn: () => CreateInfiniteQueryOptions,
injector?: Injector,
) {
return assertInjector(injectInfiniteQuery, injector, () =>
Expand Down
10 changes: 3 additions & 7 deletions packages/angular-query-experimental/src/inject-mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@ export function injectMutation<
TVariables = void,
TContext = unknown,
>(
optionsFn: (
client: QueryClient,
) => CreateMutationOptions<TData, TError, TVariables, TContext>,
optionsFn: () => CreateMutationOptions<TData, TError, TVariables, TContext>,
injector?: Injector,
): CreateMutationResult<TData, TError, TVariables, TContext> {
return assertInjector(injectMutation, injector, () => {
Expand All @@ -58,7 +56,7 @@ export function injectMutation<
TError,
TVariables,
TContext
>(queryClient, optionsFn(queryClient))
>(queryClient, optionsFn())
const mutate: CreateMutateFunction<
TData,
TError,
Expand All @@ -70,9 +68,7 @@ export function injectMutation<

effect(() => {
observer.setOptions(
runInInjectionContext(currentInjector, () =>
optionsFn(queryClient),
),
runInInjectionContext(currentInjector, () => optionsFn()),
)
})

Expand Down
26 changes: 15 additions & 11 deletions packages/angular-query-experimental/src/inject-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { QueryObserver } from '@tanstack/query-core'
import { assertInjector } from './util/assert-injector/assert-injector'
import { createBaseQuery } from './create-base-query'
import type { Injector } from '@angular/core'
import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core'
import type { DefaultError, QueryKey } from '@tanstack/query-core'
import type {
CreateQueryOptions,
CreateQueryResult,
Expand Down Expand Up @@ -56,9 +56,12 @@ export function injectQuery<
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
optionsFn: (
client: QueryClient,
) => DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
optionsFn: () => DefinedInitialDataOptions<
TQueryFnData,
TError,
TData,
TQueryKey
>,
injector?: Injector,
): DefinedCreateQueryResult<TData, TError>

Expand Down Expand Up @@ -105,9 +108,12 @@ export function injectQuery<
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
optionsFn: (
client: QueryClient,
) => UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
optionsFn: () => UndefinedInitialDataOptions<
TQueryFnData,
TError,
TData,
TQueryKey
>,
injector?: Injector,
): CreateQueryResult<TData, TError>

Expand Down Expand Up @@ -154,9 +160,7 @@ export function injectQuery<
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
optionsFn: (
client: QueryClient,
) => CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
optionsFn: () => CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
injector?: Injector,
): CreateQueryResult<TData, TError>

Expand Down Expand Up @@ -198,7 +202,7 @@ export function injectQuery<
* @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
*/
export function injectQuery(
optionsFn: (client: QueryClient) => CreateQueryOptions,
optionsFn: () => CreateQueryOptions,
injector?: Injector,
) {
return assertInjector(injectQuery, injector, () =>
Expand Down

0 comments on commit 4aff846

Please sign in to comment.