reactjsnext.jsswr

SWR pagination with object as search queries


I have been using SWR for pagination to display data on the page. At first it was a simple API with 2 query strings: page and size.

const fetcher = (...args) => fetch(...args).then((res) => res.json());

const { data, error } = useSWR(
  `/api/pager?page=${pageIndex}&size=${pageSize}`,
  fetcher
);

So far so good. Now I want to add search feature to the data. The search criteria can be complex. Apart from searching on string, I also want to search on Date, score and some other fields. Putting them in the URL search queries seems not efficient as the URL will become sooooo long.

const searchCriteria = {
  description: "some foo",
  startDate: new Date("2023-04-01"),
  endDate: new Date("2023-04-30"),
  submitted: true
}

Is there a way to do pagination with SWR by providing an object? The official doc looks vague to me. Appreciate if example code can be provided.


Solution

  • If you can modify the API then use POST method and send your data in the body:

    const fetcher = ({ url, data }) => fetch(url, {
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    }).then((res) => res.json());
    
    const searchCriteria = {
      description: "some foo",
      startDate: new Date("2023-04-01"),
      endDate: new Date("2023-04-30"),
      submitted: true
    }
    
    const { data, error } = useSWR({
        url: `/api/pager`,
        data: { ...searchCriteria. page: pageIndex, size: pageSize  }
      },
      fetcher
    );
    

    Otherwise you can use URLSearchParams to concatenate your search params with the url:

    const searchParams = new URLSearchParams(searchCriteria);
    
    const { data, error } = useSWR(
      `/api/pager?page=${pageIndex}&size=${pageSize}&${searchParams.toString()}`,
      fetcher
    );