Reputation: 159
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)
}
Upvotes: 2
Views: 1455
Reputation: 78
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.
Upvotes: 3