#GET request fetching empty array twice then actual data

10 messages · Page 1 of 1 (latest)

zealous talon
#

I'm making a fetch request to a API route and populating the data in page, like this

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-data

import 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.

fading socketBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

marble tartan
#

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

#

If you really want to fetch client-side for whatever reason instead of doing it server-side use SWR or react-query.

zealous talon
#

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