SWR不提供陈旧数据



我认为SWR应该在页面加载时返回陈旧的数据,然后用API的新信息更新视图。

我做了一个基本的Nextjs应用程序,带有简单的API超时;加载"-对于我添加到API中的5秒超时-每次。我的印象是,一旦API调用返回,它应该在更新之前提供以前缓存的版本?

Vercel URL-https://swr-test-mkhx72bz3-webknit.vercel.app/

回购-https://github.com/webknit/swr-test

index.js

import useSWR from 'swr'
const fetcher = (...args) => fetch(...args).then(res => res.json())
export default function Home() {
const { data, error } = useSWR('/api/hello', fetcher)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return (
<div>{data.num}</div>
)
}

hello.js

export default function handler(req, res) {
setTimeout(() => {
res.status(200).json({ num: Math.floor(Math.random() * 5000) })
}, 5000)

}

我不是专家;每次";你是说每次重新加载网页的时候?SWR不会在刷新网页之间为您缓存值。

在这种情况下,缓存意味着使用相同swr键("/api/hello"(的两个组件将只导致对api的一次调用。因此,哪个组件首先调用swr将获得api响应,第二个组件将从缓存中获得相同的值。

但是swr以后仍然可以多次调用api;重新验证";并将更新后的响应发送到使用该密钥的两个(或所有(组件。

最新更新