From d9c6f1ea87f47c59435f7eda89dd9ec1cc7e7096 Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Tue, 17 Aug 2021 14:43:17 +0200 Subject: [PATCH] fix: add trigger symbol --- src/use-swr.ts | 13 ++++++++++++- src/utils/helper.ts | 4 ++++ trigger/index.ts | 5 +++-- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/use-swr.ts b/src/use-swr.ts index e8e5aefec..d028f8e2d 100644 --- a/src/use-swr.ts +++ b/src/use-swr.ts @@ -3,7 +3,12 @@ import defaultConfig from './utils/config' import { wrapCache, SWRGlobalState, GlobalState } from './utils/cache' import { IS_SERVER, rAF, useIsomorphicLayoutEffect } from './utils/env' import { serialize } from './utils/serialize' -import { isThenable, isUndefined, UNDEFINED } from './utils/helper' +import { + isThenable, + isUndefined, + UNDEFINED, + TriggerSymbol +} from './utils/helper' import ConfigProvider from './utils/config-context' import useStateWithDeps from './utils/state' import withArgs from './utils/resolve-args' @@ -449,6 +454,12 @@ export const useSWRHandler = ( // `mutate`, but bound to the current key. const boundMutate: SWRResponse['mutate'] = useCallback( (newData, shouldRevalidate) => { + // To add internal options without affecting the API, we use Symbol as the + // argument to specialize it. + if ((newData as any) === TriggerSymbol) { + return revalidate() + } + return internalMutate(cache, keyRef.current, newData, shouldRevalidate) }, // `cache` isn't allowed to change during the lifecycle diff --git a/src/utils/helper.ts b/src/utils/helper.ts index b01d1d1a9..90a1687ab 100644 --- a/src/utils/helper.ts +++ b/src/utils/helper.ts @@ -1,6 +1,10 @@ // `undefined` can possibly be replaced by something else. export const UNDEFINED: undefined = ({} as any)[0] + export const isUndefined = (v: any) => v === UNDEFINED export const isThenable = (v: any): v is Promise => v && typeof v.then === 'function' + +export const TriggerSymbol = Symbol.for('swr.t') + export const noop = () => {} diff --git a/trigger/index.ts b/trigger/index.ts index 3442aa7a1..303068845 100644 --- a/trigger/index.ts +++ b/trigger/index.ts @@ -10,6 +10,7 @@ import useSWR, { import { useCallback, useRef } from 'react' import { withMiddleware } from '../src/utils/with-middleware' +import { TriggerSymbol } from '../src/utils/helper' export const trigger = (((useSWRNext: SWRHook) => ( key: Key, @@ -48,8 +49,8 @@ export const trigger = (((useSWRNext: SWRHook) => ( // Assign extra arguments to the ref, so the fetcher can access them later. extraArgsRef.current = extraArgs - // Mutate the SWR data and return the result. - return swr.mutate() + // Trigger a revalidation. + return swr.mutate(TriggerSymbol) }, [swr.mutate] )