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);

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.

Further reading

Problem with a question

State Management · Middle · question 40

Test yourself

Take the State Management · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz