#fetching data error | Next.JS, SWR

20 messages · Page 1 of 1 (latest)

frank valve
#

page.tsx -->

"use client"

import useSWR from "swr"

type TestType = {
    userId: number,
    id: number,
    title: string,
    completed: boolean
}

async function fetcher(key: string) {
  return fetch(key).then((res) => res.json() as Promise<TestTypenull>)
}

const Page = () => {

    const { data } = useSWR(`/api/test/1`, fetcher, { refreshInterval1000 }) || null
    console.log(data)

    return (
        <div>Test</div>
    )
}

export default Page

api/test/[id]/route.ts -->

export async function GET({params}: {params: {id: string}}) {
    try {
        const res = await fetch(`https://jsonplaceholder.typicode.com/todos/${params.id}`)
        const data = await res.json()
        return Response.json(data)
    } catch (error) {
        return new Response("Internal Error", {status: 500})
    }
}

I get an error when I use it this way. But when I replace {params.id} with '1' I don't get any errors. What is the reason?

shrewd solarBOT
#

🔎 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)

frank valve
#

Actually, I wrote
const res = await fetch(https://jsonplaceholder.typicode.com/todos/{params.id})
but it seems broken due to the error in discord.

plain basalt
frank valve
plain basalt
#

add a ts or js after the third '`'

frank valve
frank valve
plain basalt
#

params is in second

frank valve
plain basalt
#

what error you get?

#
await fetch(`https://jsonplaceholder.typicode.com/todos/${params.id}`)
frank valve
plain basalt
#
export async function GET(req: Request, {params}: {params: {id: string}}) {
    try {
        const res = await fetch(`https://jsonplaceholder.typicode.com/todos/{params.id}`)
        const data = await res.json()
        return Response.json(data)
    } catch (error) {
        console.log(error)
        return new Response("Internal Error", {status: 500})
    }
}
#

log the error and see

frank valve
#

wait, i will send ss

shrewd solarBOT
#
✅ Success!

This question has been marked as answered! If you have any other questions, feel free to create another post

Jump to answer
plain basalt
#

it works?