skip to Main Content

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


  1. 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 Fetching

    Use null or pass a function as key to conditionally fetch data. If the function throws or returns a falsy value, SWR will not start the request.

    // conditionally fetch
    const { data, error, isLoading } = useSWR(selectedMatch ? ['api/model', selectedMatch] : null, fetcher);
     
    // ...or return a falsy value
    const { data, error, isLoading } = useSWR(() => selectedMatch? ["api/model", selectedMatch] : null, fetcher)
    

    you can do that and based on the value of data you decide what to return

    Login or Signup to reply.
  2. You can pass null as the key to the useSWR hook when you don’t want to fetch:

    export default function Model() {
      const searchParams = useSearchParams();
      const selectedMatch = searchParams.get('data');
      const { data, error, isLoading } = useSWR(selectedMatch ? ['api/model', 
        selectedMatch] : null, fetcher);
    
      return (...)
      
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search