应用程序/auth-callback/page.tsx
import { useRouter, useSearchParams } from 'next/navigation'
import React from 'react'
import { trpc } from '../_trpc/client'
const Page = () => {
const router = useRouter()
const searchParmas = useSearchParams()
const origin = searchParmas.get('origin')
const {data,isLoading} = trpc.authcallback.useQuery( undefined, {
onSuccess:({success})=>{
if(success){
router.push('/dashboard')
}
}
})
}
export default Page
API 端点(trpc/index.ts)
import { getKindeServerSession } from '@kinde-oss/kinde-auth-nextjs/server';
import { publicProcedure, router } from './trpc';
import { TRPCError } from '@trpc/server';
export const appRouter = router({
authcallback: publicProcedure.query( async ()=>{
const {getUser} = getKindeServerSession()
const user = await getUser()
if(!user?.id || !user?.email) {
throw new TRPCError({code:"UNAUTHORIZED"})
}
return {success:true}
})
});
export type AppRouter = typeof appRouter;
您好,在上面的代码中,我想从我的 api 端点访问成功响应,为此我使用 tRPC 和 @tanstack/react-query 但我无法访问回调(onSuccess)。
我如何访问它或可以帮助我的替代选项。
成功是一个布尔值;
'use client'
import { useSearchParams } from 'next/navigation'
import { useRouter } from 'next/router'
import { trpc } from '../_trpc/client'
import { useEffect } from 'react'
export default async function AuthCallback () {
const router = useRouter()
const searchParams = useSearchParams()
const origin = searchParams.get('origin')
const { data, error } = trpc.authCallback.useQuery(undefined, {
retry: true,
retryDelay: 500
})
useEffect(() => {
if (data?.success === true) {
router.push((origin != null) ? `/${origin}` : '/dashboard')
return
}
if (error?.data?.code === 'UNAUTHORIZED') {
router.push('/sign-in')
}
}, [data, error])
return (
<div className='w-full mt-24 flex justify-center'>
<div className='flex flex-col items-center gap-2'>
<h3 className='font-semibold text-xl'>
Setting up your account...
</h3>
<p>You will be redirected automatically.</p>
</div>
</div>
)
}