GET request fetching empty array twice then actual data
Answered
Naeemgg posted this in #help-forum
NaeemggOP
I'm making a fetch request to a API route and populating the data in page, like this
this is
I dont know why
const [Records,setRecords] = useState([])
useEffect(()=>{
const getData =async()=> {
const response = await fetch(`/api/get-data?name=${session.data?.user?.name}`)
const data = await response.json()
console.log(data)
setRecords(data);}
getData()
},[session.data?.user?.name])
return(Records.map((record,index)=><span key={record.id}>{record.name})</span>)this is
/api/get-dataimport prisma from "@/prisma/client";
import { NextRequest, NextResponse } from "next/server";
export async function GET(req:NextRequest){
const name=req.nextUrl.searchParams.get("name")
try {
const details = await prisma.doc.findMany({where:{name}})
return NextResponse.json(details,{status:200})
} catch (error) {
console.log(error)
return NextResponse.json({msg:"Error"},{status:503})}}
export const revalidate = 0;I dont know why
fetch() is making request thrice to the route as you can see in the attached image, first two times I'm getting empty array then the actual data. I have tried no-store, no-cache in fetch() but using that was resulting in getting first time exatct data then empty array.Answered by Giant panda
If you really want to fetch client-side for whatever reason instead of doing it server-side use SWR or react-query.
8 Replies
Giant panda
Two of the three runs are due to strict mode in dev mode.
The third is probably a bug due to your very unconventional way of fetching data
Giant panda
If you really want to fetch client-side for whatever reason instead of doing it server-side use SWR or react-query.
Answer
tried making a separate function to get the data
but still facing the same issue
that's why I went for client side data fetching
Ahhh I seriously forgot on server side we need to pass full url like
http://locahost:3000/api/get-data instead of just /api/get-data