Skip to content
Open
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
11 changes: 10 additions & 1 deletion src/mutation/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,20 @@ const mutation = (<Data, Error>() =>

const trigger = useCallback(
async (arg: any, opts?: SWRMutationConfiguration<Data, Error>) => {
const [serializedKey, resolvedKey] = serialize(keyRef.current)
//If null is received as the key, ignore it.
const keyVal = keyRef.current

const resolvedKeyForCheck =
typeof keyVal === 'function' ? keyVal() : keyVal

if (!resolvedKeyForCheck) return

const [serializedKey, resolvedKey] = serialize(keyVal)

if (!fetcherRef.current) {
throw new Error('Can’t trigger the mutation: missing fetcher.')
}

if (!serializedKey) {
throw new Error('Can’t trigger the mutation: missing key.')
}
Expand Down
16 changes: 16 additions & 0 deletions test/use-swr-mutation-null-keys.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { renderHook } from '@testing-library/react'
import useSWRMutation from '../src/mutation/index'

describe('useSWRMutation - Null Key', () => {
it('should not log an error when the key is null', async () => {
const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
const fetcher = jest.fn()

const { result } = renderHook(() => useSWRMutation(null, fetcher))

await result.current.trigger()

expect(consoleSpy).not.toHaveBeenCalled()
consoleSpy.mockRestore()
})
})
2 changes: 1 addition & 1 deletion test/use-swr-remote-mutation.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1110,7 +1110,7 @@ describe('useSWR - remote mutation', () => {
fireEvent.click(screen.getByText('pending'))
await waitForNextTick()

expect(error.message).toBe('Can’t trigger the mutation: missing key.')
expect(error).toBeNull()
})

it('should call `onError` and `onRejected` but do not call `onSuccess` if value an error is cast to false', async () => {
Expand Down