Ben Borgers

How to refresh data with SWR

March 25, 2020

Let's say you have a piece of data you're fetching with Vercel's SWR package:

const { data } = useSWR("/posts")

If you want to refresh this data, you can do this by making use of other values returned by useSWR.

const { data, mutate, isValidating } = useSWR("/posts")
// isValidating will be explained later

You can change the cached data for /posts by calling mutate(newData).

However, if you just run mutate(), it will refresh the data for /posts in the background. mutate knows to request the /posts endpoint again, since that's where the mutate function came from.

Bonus: isValidating

You can use isValidating to show to the user whether the data has been updated yet.

This value is true while SWR is refetching the data, and false once the data has been successfully returned.

You can use isValidating to conditionally show a message that says something like Updating... while new data is being fetched.

More blog posts

Subscribe to my newsletter for a monthly round-up of new blog posts and projects Iā€™m working on!

Twitter ↗ RSS feed ↗