From b327ad604aa5201e1d9e717d84c5583acef6cd17 Mon Sep 17 00:00:00 2001 From: Key5n Date: Mon, 17 Jun 2024 23:58:12 +0900 Subject: [PATCH] feat: force to set `populateCache` option with proper type when a value of different value is assigned to mutate issue: https://github.com/vercel/swr/issues/2975 --- src/_internal/types.ts | 22 ++++++++++++++++++---- src/infinite/index.ts | 12 ++---------- src/infinite/types.ts | 25 +++++++++++++++++++++---- 3 files changed, 41 insertions(+), 18 deletions(-) diff --git a/src/_internal/types.ts b/src/_internal/types.ts index f3cdba5ed..b65b1ab08 100644 --- a/src/_internal/types.ts +++ b/src/_internal/types.ts @@ -439,10 +439,24 @@ export interface ScopedMutator { * @typeParam Data - The type of the data related to the key * @typeParam MutationData - The type of the data returned by the mutator */ -export type KeyedMutator = ( - data?: Data | Promise | MutatorCallback, - opts?: boolean | MutatorOptions -) => Promise +export type KeyedMutator = { + ( + data?: Data | Promise | MutatorCallback, + opts?: boolean | MutatorOptions + ): Promise + ( + data: + | MutationData + | Promise + | MutatorCallback, + opts: Omit, 'populateCache'> & { + populateCache: ( + result: MutationData, + currentData: Data | undefined + ) => Data + } + ): Promise +} export type SWRConfiguration< Data = any, diff --git a/src/infinite/index.ts b/src/infinite/index.ts index f410b5bef..7c4204874 100644 --- a/src/infinite/index.ts +++ b/src/infinite/index.ts @@ -19,7 +19,6 @@ import { import type { BareFetcher, SWRHook, - MutatorCallback, Middleware, GlobalState } from '../_internal' @@ -238,16 +237,9 @@ export const infinite = ((useSWRNext: SWRHook) => config ) - const mutate = useCallback( + const mutate = useCallback>( // eslint-disable-next-line func-names - function ( - data?: - | undefined - | Data[] - | Promise - | MutatorCallback, - opts?: undefined | boolean | SWRInfiniteMutatorOptions - ) { + function (data?: any, opts?: any) { // When passing as a boolean, it's explicitly used to disable/enable // revalidation. const options = diff --git a/src/infinite/types.ts b/src/infinite/types.ts index 4237b6aba..2c5204d6c 100644 --- a/src/infinite/types.ts +++ b/src/infinite/types.ts @@ -47,10 +47,27 @@ interface SWRInfiniteRevalidateFn { (data: Data, key: Arguments): boolean } -export type SWRInfiniteKeyedMutator = ( - data?: Data | Promise | MutatorCallback, - opts?: boolean | SWRInfiniteMutatorOptions -) => Promise +export type SWRInfiniteKeyedMutator = { + ( + data?: Data | Promise | MutatorCallback, + opts?: boolean | SWRInfiniteMutatorOptions + ): Promise + ( + data: + | MutationData + | Promise + | MutatorCallback, + opts: Omit< + SWRInfiniteMutatorOptions, + 'populateCache' + > & { + populateCache: ( + result: MutationData, + currentData: Data | undefined + ) => Data + } + ): Promise +} export interface SWRInfiniteMutatorOptions extends Omit, 'revalidate'> {