Skip to content
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

feat: add meta as argument for key filter #2161

Closed
wants to merge 3 commits into from
Closed
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
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) => 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)
keyFilter((cache.get(key) as { _k: Arguments })._k, meta)
) {
matchedKeys.push(key)
}
Expand Down
19 changes: 18 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,20 @@ describe('useSWR - local mutation', () => {
<span
data-testid="clear-all"
onClick={async () => {
const res = await mutate(() => true, undefined, false)
const res = await mutate(
(_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 @@ -1604,6 +1615,12 @@ describe('useSWR - local mutation', () => {
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