How to Conditionally Load Data with SWR
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:
1 | import fetcher from 'lib/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