每次请求都在客户端组件上使用SWR获取数据.Next.js 13.3 + SWR



Next.js 13.3 with app dir。我有一个非常简单的显示日期的组件。他显示它只有1次,之后它不再更新,直到我重建它。在Next.js 12中,这是不同的(刷新页面-更新数据)。我做错了什么?我不知道如何使它在每次请求时都更新日期。

为什么SWR不更新每个请求的信息?

api/hello/route.ts


export async function GET(request: Request) {
// const { searchParams } = new URL(request.url);
const response = await fetch(
"https://timeapi.io/api/Time/current/zone?timeZone=Europe/Kiev",
{ cache: "no-cache" }
);
const data = await response.json();
console.log(data);
return NextResponse.json(data);
}

time.tsx

"use client";
import useSWR from "swr";
import { fetcher } from "~/lib/fetcher";
export const Time = () => {
const { data, error, isLoading } = useSWR("api/hello", fetcher);
if (error) {
return <div>error</div>;
}
if (isLoading) return <div>loading...</div>;
console.log(data);
return (
<div>
<div>{data.dateTime}</div>
</div>
);
};

fetcher.ts

export const fetcher = (...args: any) => fetch(...args).then(res => res.json())

page.tsx

import { Inter } from "next/font/google";
import { Time } from "~/components/time";
const inter = Inter({ subsets: ["latin"] });
export const revalidate = 0;
export default async function Home() {
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<Time />
</main>
);
}

此代码用于刷新页面刷新时间(next: latest):

import useSWR, { SWRConfig } from "swr";
import { getTime } from "../lib/libTime";
const fetcher = (url: any) => fetch(url).then((res) => res.json());
export async function getStaticProps () {
const mytime = await getTime()

return {
props: {
fallback: {
'/api/time': mytime
}
}
}
}

function MyTime() {
const { data } = useSWR('/api/time', fetcher)
if (!data) return <>"Loading...";</>
return (<><h1>{data.data.dateTime}</h1></>)
}

const SWR=({ fallback }:any)=> {
return (
<SWRConfig value={{ fallback }}>
<MyTime />
</SWRConfig>
);
}
export default SWR;

相关内容

  • 没有找到相关文章

最新更新