When using SWR, you may encounter a situation where you only want to send a request if you have certain data available. For example, you might need to determine if the user is logged in before making a request to the /api/user
endpoint to fetch the user’s data. This can be achieved using the following approach:
import fetcher from 'lib/fetcher'
...
const { data: userData } = useSWR(session && session.user ? `/api/user` : null, fetcher)
In this code snippet, the first parameter of the useSWR
hook is the URL. If it is set to null
, SWR will not perform the request, effectively solving the initial problem.
Tags: SWR, data loading, conditional fetching