Home > Software design >  Integration of 'sort by' (and other filters) with SvelteKit
Integration of 'sort by' (and other filters) with SvelteKit

Time:01-18

I have a backend route '/products' (using ExpressJS and Prisma) that returns a list of all products, however it also has some query parameters that can be used to specify futher, namely:

  • page (and count): used for pagination
  • sort and sortDir: used for sorting by a value in a specific direction (desc or asc)
  • category: comma separated list of categories to search by

I load the products on the frontend SvelteKit project in page.server.ts and display them in a table format. However, when the user changes, for instance, the sort direction, how would I update the page data using a new route (namely the original one, with sortDir=desc). Is there some way of invalidating the query and replacing it with a new one, with the correct search parameters?

Or is there some other way that this is normally implemented in production?

CodePudding user response:

By using searchParams you can read the values in the load function:

//  page.server.js
export async function load({ fetch, url }) => {
  const sortDir = url.searchParams.get("sortDir")
  return {
    products: await ...,
  };
};

Accessing the searchParam will let SvelteKit know to invalidate and rerun/reload the page data when the parameter changes.

To change the searchParam use either regular urls: <a href="?sortDir=asc">ASC</a> or use the goto from the $app/navigation module.

PS. You don't need a separate express backend, you can access prisma directly from page.server.js files.

  • Related