Skip to content

fix: Ensure mutate accepts undefined as the data #1515

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Oct 9, 2021
Merged
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
14 changes: 8 additions & 6 deletions src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,9 +325,10 @@ export const useSWRHandler = <Data = any, Error = any>(

// Similar to the global mutate, but bound to the current cache and key.
// `cache` isn't allowed to change during the lifecycle.
// eslint-disable-next-line react-hooks/exhaustive-deps
const boundMutate: SWRResponse<Data, Error>['mutate'] = useCallback(
(newData, shouldRevalidate) =>
internalMutate(cache, keyRef.current, newData, shouldRevalidate),
// By using `bind` we don't need to modify the size of the rest arguments.
internalMutate.bind(UNDEFINED, cache, () => keyRef.current),
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
)
Expand Down Expand Up @@ -360,12 +361,13 @@ export const useSWRHandler = <Data = any, Error = any>(
error: updatedError,
isValidating: updatedIsValidating
},
// if data is undefined we should not update stateRef.current.data
!compare(stateRef.current.data, updatedData)
? {
// Since `setState` only shallowly compares states, we do a deep
// comparison here.
compare(stateRef.current.data, updatedData)
? UNDEFINED
: {
data: updatedData
}
: null
)
)
}
Expand Down
31 changes: 19 additions & 12 deletions src/utils/mutate.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,34 @@
import { serialize } from './serialize'
import { isUndefined, isFunction, UNDEFINED } from './helper'
import { isFunction, UNDEFINED } from './helper'
import { SWRGlobalState, GlobalState } from './global-state'
import { broadcastState } from './broadcast-state'
import { getTimestamp } from './timestamp'

import { Key, Cache, MutatorCallback } from '../types'

export const internalMutate = async <Data>(
cache: Cache,
_key: Key,
_data?: Data | Promise<Data | undefined> | MutatorCallback<Data>,
revalidate = true
...args: [
Cache,
Key,
undefined | Data | Promise<Data | undefined> | MutatorCallback<Data>,
undefined | boolean
]
) => {
const [cache, _key] = args
// Fallback to `true` if it's not explicitly set to `false`
const revalidate = args[3] !== false
let _data = args[2]

// Serilaize key
const [key, , keyErr] = serialize(_key)
if (!key) return

const [, , MUTATION_TS, MUTATION_END_TS] = SWRGlobalState.get(
cache
) as GlobalState

// If there is no new data to update, we revalidate the key.
if (isUndefined(_data)) {
// If there is no new data provided, revalidate the key with current state.
if (args.length < 3) {
// Revalidate and broadcast state.
return broadcastState(
cache,
Expand All @@ -43,8 +51,7 @@ export const internalMutate = async <Data>(
try {
_data = (_data as MutatorCallback<Data>)(cache.get(key))
} catch (err) {
// if `_data` function throws an error synchronously, it shouldn't be cached
_data = UNDEFINED
// If it throws an error synchronously, we shouldn't update the cache.
error = err
}
}
Expand All @@ -68,14 +75,14 @@ export const internalMutate = async <Data>(
data = _data
}

if (!isUndefined(data)) {
// update cached data
// Only update cached data if there's no error. Data can be `undefined` here.
if (!error) {
cache.set(key, data)
}
// Always update or reset the error.
cache.set(keyErr, error)

// Reset the timestamp to mark the mutation has ended
// Reset the timestamp to mark the mutation has ended.
MUTATION_END_TS[key] = getTimestamp()

// Update existing SWR Hooks' internal states:
Expand Down
2 changes: 1 addition & 1 deletion test/use-swr-error.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ describe('useSWR - error', () => {
// mount
await screen.findByText('hello, error')

await act(() => mutate(undefined, true))
await act(() => mutate())
// initial -> first error -> mutate -> receive another error
// error won't be cleared during revalidation
expect(errors).toEqual([null, 'error', 'error'])
Expand Down
47 changes: 47 additions & 0 deletions test/use-swr-local-mutation.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -833,4 +833,51 @@ describe('useSWR - local mutation', () => {
screen.getByText('data:data')
screen.getByText('isValidating:false')
})

it('should be able to mutate data to undefined', async () => {
const key = createKey()
function Page() {
const { data, mutate } = useSWR(key, () => 'foo')
return (
<>
<div>data: {String(data)}</div>
<button onClick={() => mutate(undefined, false)}>mutate</button>
</>
)
}

renderWithConfig(<Page />)
await screen.findByText('data: foo')

fireEvent.click(screen.getByText('mutate'))
await screen.findByText('data: undefined')
})

it('should be able to mutate data to undefined asynchronously', async () => {
const key = createKey()
function Page() {
const { data, mutate } = useSWR(key, () => 'foo')
return (
<>
<div>data: {String(data)}</div>
<button
onClick={() =>
mutate(
() => new Promise(res => setTimeout(() => res(undefined), 10)),
false
)
}
>
mutate
</button>
</>
)
}

renderWithConfig(<Page />)
await screen.findByText('data: foo')

fireEvent.click(screen.getByText('mutate'))
await screen.findByText('data: undefined')
})
})