Route handler (problem)
Unanswered
Cuban Crocodile posted this in #help-forum
Cuban CrocodileOP
After creating the API route handler, I have a function that handles GET. then I called fetch in some component and did await res.json() and after that I have no type for body. How to get the type so that typescript has values automatically based on the body instead of manually setting it? I want to infer data based on GET function.
3 Replies
Cuban CrocodileOP
import { NextResponse } from "next/server"
export async function GET(request: Request)
{
const {searchParams} = new URL(request.url)
const query = searchParams.get('query')
const page = searchParams.get('page')
const res = await fetch(`pixabayLink`) //I removed link
const fetchedData: { totalHits: number, hits: {webformatURL: string}[]} = await res.json()
const value = {
isNext: fetchedData.totalHits > (Number(page) * 8),
isPrevious: Number(page) > 1,
images: fetchedData.hits.map(el => ({url: el.webformatURL}))
}
return Response.json({value})
} function Modal({ setValue }: ModalProps) {
const getImages = async () => {
const data = await fetch("/api/?query=plane&page=1");
const d = await data.json();
setImages(d.value.images); //HERE IS THE PROBLEM
};@Cuban Crocodile After creating the API route handler, I have a function that handles GET. then I called fetch in some component and did await res.json() and after that I have no type for body. How to get the type so that typescript has values automatically based on the body instead of manually setting it? I want to infer data based on GET function.
you can't, because it's like fetching an external endpoint: you don't know what's coming back. But you control your endpoint so you know what you return back. Like that you can get the type of your endpoint. In your case from value. Type that variable or Infer that variable and export the type. Then you can read and apply the type
@Cuban Crocodile solved?