Ask Your Question
1

How can I limit the number of requests sent by useSWR to just one for a specific key in my Next.js application?

asked 2021-07-14 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-07-21 07:00:00 +0000

david gravatar image

You can use the option revalidateOnMount and set it to false. This will ensure that useSWR only sends a request on the initial mount of the component and will not revalidate the data again.

Here's an example:

import useSWR from 'swr';

function MyComponent() {
  const { data, error } = useSWR('/api/some-data', fetcher, { revalidateOnMount: false });

  if (error) return <div>Error</div>;
  if (!data) return <div>Loading...</div>;

  return <div>{data}</div>;
}

In this example, useSWR will only send one request to /api/some-data on the initial mount of the component and will use the cached data for subsequent renders.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-07-14 11:00:00 +0000

Seen: 9 times

Last updated: Jul 21 '21