Search code examples
reactjsnext.jsreact-querytanstackreact-querytrpc

onSuccess and onError are not working in newest version of React-Query?


Errors show up in onSuccess and onError functions. Did some research and turns out these functions are depcrecated in newest version of React-Query.

"use client"

import { useRouter, useSearchParams } from 'next/navigation'
import { trpc } from '../_trpc/client'
import { Loader2 } from 'lucide-react'

const Page = () => {
  const router = useRouter()

  const searchParams = useSearchParams()
  const origin = searchParams.get('origin')

  trpc.authCallback.useQuery(undefined, {
    onSuccess: ({ success }) => {
      if (success) {
        // user is synced to db
        router.push(origin ? `/${origin}` : '/dashboard')
      }
    },
    onError: (err) => {
      if (err.data?.code === 'UNAUTHORIZED') {
        router.push('/sign-in')
      }
    },
    retry: true,
    retryDelay: 500,
  })

  return (
    <div className='w-full mt-24 flex justify-center'>
      <div className='flex flex-col items-center gap-2'>
        <Loader2 className='h-8 w-8 animate-spin text-zinc-800' />
        <h3 className='font-semibold text-xl'>
          Setting up your account...
        </h3>
        <p>You will be redirected automatically.</p>
      </div>
    </div>
  )
}

export default Page

Tried some to use some answers from similar problems but they were written in a completely different format and didnt work/i didnt know how to apply them. This is from a YT tutorial btw and im completely new to web dev so im pretty lost here. Any workaround to this?


Solution

  • onSuccess and onError were removed from useQuery() from v5. The reasons are explained here.

    You can use useEffect hook instead. Following is the code how use can use useEffect in this scenario.

    const { data, isLoading, error } = trpc.authCallback.useQuery(undefined, {
            retry: true,
            retryDelay: 500,
        })
    
        useEffect(() => {
            if (data) {
                const { success } = data
                if (success) {
                    // user is synced to db
                    console.log('Data fetched successfully:', data);
                    router.push(origin ? `/${origin}` : '/dashboard')
                }
            }
            else if (error) {
                if (error.data?.code === 'UNAUTHORIZED') {
                    router.push('/sign-in')
                }
            }
    
        }, [data, origin, router, error]);