Skip to content

Commit

Permalink
fix: add trigger symbol
Browse files Browse the repository at this point in the history
  • Loading branch information
shuding committed Aug 17, 2021
1 parent 8b712fd commit d9c6f1e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
13 changes: 12 additions & 1 deletion src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -449,6 +454,12 @@ export const useSWRHandler = <Data = any, Error = any>(
// `mutate`, but bound to the current key.
const boundMutate: SWRResponse<Data, Error>['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
Expand Down
4 changes: 4 additions & 0 deletions src/utils/helper.ts
Original file line number Diff line number Diff line change
@@ -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<any> =>
v && typeof v.then === 'function'

export const TriggerSymbol = Symbol.for('swr.t')

export const noop = () => {}
5 changes: 3 additions & 2 deletions trigger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ((<Data, Error>(useSWRNext: SWRHook) => (
key: Key,
Expand Down Expand Up @@ -48,8 +49,8 @@ export const trigger = ((<Data, Error>(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]
)
Expand Down

0 comments on commit d9c6f1e

Please sign in to comment.