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

Fix mutateCallback types #745

Merged
merged 5 commits into from
Nov 13, 2020
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
4 changes: 2 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ export type triggerInterface = (
shouldRevalidate?: boolean
) => Promise<any>
export type mutateCallback<Data = any> = (
currentValue: Data
) => Promise<Data> | Data
currentValue: undefined | Data
) => Promise<undefined | Data> | undefined | Data
export type mutateInterface<Data = any> = (
key: keyInterface,
data?: Data | Promise<Data> | mutateCallback<Data>,
Expand Down
20 changes: 20 additions & 0 deletions test/use-swr.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1493,6 +1493,26 @@ describe('useSWR - local mutation', () => {
expect(callback).toHaveBeenCalledWith('cached data')
})

it('should call function with undefined if key not cached', async () => {
const increment = jest.fn(currentValue =>
currentValue == null ? undefined : currentValue + 1
)

await mutate('dynamic-15.1', increment, false)

expect(increment).toHaveBeenCalledTimes(1)
expect(increment).toHaveBeenLastCalledWith(undefined)
expect(increment).toHaveLastReturnedWith(undefined)

cache.set('dynamic-15.1', 42)

await mutate('dynamic-15.1', increment, false)

expect(increment).toHaveBeenCalledTimes(2)
expect(increment).toHaveBeenLastCalledWith(42)
expect(increment).toHaveLastReturnedWith(43)
})

it('should return results of the mutation', async () => {
// returns the data if promise resolved
expect(mutate('dynamic-16', Promise.resolve('data'))).resolves.toBe('data')
Expand Down