State Management · Middle · Question 40 of 75
How do you fetch data in SWR only when a condition is met?
const { data } = useSWR(userId ? `/api/user/${userId}` : null, fetcher);- ✓Correct answer: Pass
null(or a falsy key) - SWR won't make the request - 2Wrap
useSWRin anifstatement - 3Pass
enabled: falsein the options
Explanation
A null key means "don't fetch". The key can also be a function that throws or returns a falsy value while a dependency is missing - that's how dependent requests are built.