Search code examples
next.jsfetchswr

SWR doesn't work when window loses focus in Nextjs


I am using SWR in nextjs:

const fetcher = () => {
  const response = axios.get("http://localhost:3000/api/model", {
  }).then(r => r.data)
  return response;
};

export default function Model() {
  const { data, error, isLoading } = useSWR("/api/model", fetcher);
  return <p>{JSON.stringify(data)}</p>}

My /api/model is GET request to my database, and the database updates the value every second.

However, if I stay on the page, the JSON.stringify(data) won't even change; once I switch to another tap or click the background of my computer, then click back the page, the value change instantly(I don't know how to explain this kind of situation).

I want the data to keep updating when I stay on the website without any action like WebSocket. Can I do it using SWR?


Solution

  • You have experienced "revalidate on focus" strategy, when the tab is focused the data will be revalidated. This option is enabled by default.

    If you want to refetch the data based on some interval you can use refreshInterval option, example from the docs:

    useSWR('/api/todos', fetcher, { refreshInterval: 1000 })
    

    More info in the docs as always