My page receives parameters from the previous page and uses useSWR
to fetch the data base on the parameters:
export default function Model() {
const searchParams = useSearchParams();
const selectedMatch = searchParams.get("data")
if (selectedMatch == "") {
return <p>no data is found</p>}
const { data, error, isLoading } = useSWR(["api/model", selectedMatch], fetcher)
return (...)
}
It seems that react hooks useSWR
must be on top of the component before any return and condition, however, I want to handle the empty case of selectedMatch
before passing to useSWR
, how can I do it?
2
Answers
The obstacle here is that
useSWR
is a hook and cannot be called conditionally but SWR provides, let’s say, some tricks with useSWR as Conditional Fetchingyou can do that and based on the value of
data
you decide what to returnYou can pass
null
as thekey
to theuseSWR
hook when you don’t want to fetch: