SWR 不提供陈旧数据?
我的印象是,SWR 应该在使用来自 API 的新信息更新视图之前返回页面加载时的过时数据。
我已经制作了一个基本的 Nextjs 应用程序,具有简单的 API 超时,并且它每次都在“加载” - 对于我添加到 API 的 5 秒超时。我的印象是,一旦 API 调用返回,它应该在更新之前提供之前缓存的版本?
Vercel 网址 - 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)
}
I was under the impression SWR should return the stale data on page load before updating the view with the new info from the API.
I have made a basic Nextjs app with simple API timeout and it's "loading" - for the 5 second timeout I have added to the API - every time. I was under the impression it should serve the previously cached version before updating once the API call returns?
Vercel URL - https://swr-test-mkhx72bz3-webknit.vercel.app/
repo - 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)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不是专家,但“每次”是指每次重新加载网页时吗? SWR 不会为您缓存网页刷新之间的值。
在此上下文中的缓存意味着使用相同 swr 键 ('/api/hello') 的两个组件将仅导致对 api 的一次调用。因此,哪个组件首先调用 swr 将获得 api 响应,第二个组件将从缓存中获得相同的值。
但 swr 仍然可以稍后多次调用 api 来“重新验证”并将更新后的响应发送到使用该密钥的两个(或所有)组件。
I'm no expert but by "every time" do you mean every time you reload the webpage? SWR wont cache the value between refreshes of the webpage for you.
Cache in this context means that two components using the same swr key ('/api/hello') will result in just one call to the api. So which ever component calls the swr first will get the api response, and the second component will get the same value from the cache.
But swr can still call the api multiple times later on to "revalidate" and send the updated response to both (or all) components that use that key.