Home > Software engineering >  Unable to convert example of `useSwr` hook to use `react-query`'s `useMutation` hook?
Unable to convert example of `useSwr` hook to use `react-query`'s `useMutation` hook?

Time:06-06

I tried changing the useSwr hook to use:

import { useMutation } from 'react-query';

const { data: user, mutate: mutateUser } = useMutation<User>('/api/user');

But I get an error stating:

No mutationFn found

Unable to solve this. I tried adding mutationFn inside useMutation like the following & it works but it is static:

const { data: user, mutate: mutateUser } = useMutation<User>('/api/user', {
    mutationFn: () => {
      const u: User = {
        isLoggedIn: false,
        avatarUrl: '',
        login: '',
      }
      return Promise.resolve(u)
    },
  })

If I use a dynamic request using something like axios then do I need to put the fetchJson from login.tsx to mutationFn hook?

Basically, I want to use react-query instead of swr & ky instead of fetchJson & unable to find a solution?

I'm pretty sure it's really simple but haven't been able to make it work.

Stackblitz Demo → https://stackblitz.com/edit/next-iron-session-with-react-query?file=lib/useUser.ts (go to /login route, enter a github username like vvo & click Login to see the error in console)

Repo → https://github.com/deadcoder0904/next-iron-session-with-react-query

CodePudding user response:

By navigating through the documentation it seems that the first argument of the useMutation if the mutationFn and not the mutationKey

useMutation

What if the code changes to:

const { data: user, mutate: mutateUser } = useMutation<User, unknown, { username: string }>((body) => {
      return fetchJson('/api/login', {
       method: 'POST',
       headers: { 'Content-Type': 'application/json' },
       body: JSON.stringify(body),
      })
    }, {
      mutationKey: '/api/user'
    }
  })

and when you need to actually mutate

mutateUser({ username: 'Username' })
  • Related