diff --git a/src/mutation/index.ts b/src/mutation/index.ts index 363c2138b..2d3ed8ca7 100644 --- a/src/mutation/index.ts +++ b/src/mutation/index.ts @@ -47,11 +47,20 @@ const mutation = (() => const trigger = useCallback( async (arg: any, opts?: SWRMutationConfiguration) => { - 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.') } diff --git a/test/use-swr-mutation-null-keys.test.tsx b/test/use-swr-mutation-null-keys.test.tsx new file mode 100644 index 000000000..d6f1ecb74 --- /dev/null +++ b/test/use-swr-mutation-null-keys.test.tsx @@ -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() + }) +}) diff --git a/test/use-swr-remote-mutation.test.tsx b/test/use-swr-remote-mutation.test.tsx index bdaef55eb..05200fbca 100644 --- a/test/use-swr-remote-mutation.test.tsx +++ b/test/use-swr-remote-mutation.test.tsx @@ -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 () => {