Skip to content

Commit

Permalink
pass down meta and add test
Browse files Browse the repository at this point in the history
  • Loading branch information
huozhi committed Sep 17, 2022
1 parent 8ce5479 commit 5a6fa0f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
5 changes: 3 additions & 2 deletions _internal/utils/mutate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type {
Key
} from '../types'

type KeyFilter = (key: Arguments | undefined, serializedKey: string) => boolean
type KeyFilter = (key: Arguments | undefined, { serializedKey } : { serializedKey: string }) => boolean
type MutateState<Data> = State<Data, any> & {
// The previously committed data.
_c?: Data
Expand Down Expand Up @@ -60,10 +60,11 @@ export async function internalMutate<Data>(
const keyFilter = _key
const matchedKeys: Key[] = []
for (const key of cache.keys()) {
const meta = { serializedKey: key }
if (
// Skip the special useSWRInfinite keys.
!key.startsWith('$inf$') &&
keyFilter((cache.get(key) as { _k: Arguments })._k, key)
keyFilter((cache.get(key) as { _k: Arguments })._k, meta)
) {
matchedKeys.push(key)
}
Expand Down
21 changes: 20 additions & 1 deletion test/use-swr-local-mutation.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1563,11 +1563,14 @@ describe('useSWR - local mutation', () => {
it('should remove all key value pairs when clear cache through key filter', async () => {
const key = createKey()
const mutationOneResults = []
const collectedKeys = []

function Page() {
const { data: data1 } = useSWR(key + 'first')
const { data: data2 } = useSWR(key + 'second')
const { data: data3 } = useSWR([key + 'third'])
const { mutate } = useSWRConfig()

return (
<div>
<span
Expand All @@ -1582,12 +1585,21 @@ describe('useSWR - local mutation', () => {
<span
data-testid="clear-all"
onClick={async () => {
const res = await mutate(() => true, undefined, false)
const res = await mutate(
(_key, { serializedKey }) => {
console.log('serializedKey', _key, serializedKey)
collectedKeys.push([_key, serializedKey])
return true
},
undefined,
false
)
mutationOneResults.push(...res)
}}
/>
<p>first:{data1}</p>
<p>second:{data2}</p>
<p>third:{data3}</p>
</div>
)
}
Expand All @@ -1597,13 +1609,20 @@ describe('useSWR - local mutation', () => {
fireEvent.click(screen.getByTestId('mutator-filter-all'))
await nextTick()


await screen.findByText('first:value-first')
await screen.findByText('second:value-second')

// reset all keys to undefined
fireEvent.click(screen.getByTestId('clear-all'))
await nextTick()

expect(collectedKeys).toEqual([
[key + 'first', key + 'first'],
[key + 'second', key + 'second'],
[[key + 'third'], serialize([key + 'third'])[0]],
])

await screen.findByText('first:')
await screen.findByText('second:')

Expand Down

0 comments on commit 5a6fa0f

Please sign in to comment.