Next.js Discord

Discord Forum

Filter data using Server Actions?

Unanswered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
Hello 👋

This is usually something I'd do with state, hook, or context, but these solutions seem to want to send me down the client-side route. I think I need to use Server Actions but I can't quite wrap my head around it...

Below is a super basic reproduction, pretty much exactly what I'm working with... My getArtists request is a single request that returns everything in one go. All of the transformations will be done on my side with no further requests.

Assuming getArtists return a huge json dump of Artists. How do I then filter by genre?


async function getArtists(param) {
  const res = await fetch(
    `https://my-api.com/${param}`
  );
  return res.json();
}

export default async function Page({ params: { param } }) {
  const artists = await getArtists(param);

  async function filterByGenre(genre) {
    "use server";

    const filteredArtists = artists.filter((artist) => artist.genre === genre);
    // how do I update my artist data to be reflected in the UI?
  }

  return (
    <div>
      <button onClick={() => filterByGenre("musicals")}>Filter By Musicals</button>
      {artists.map(artist => artist....)}
    </div>
  );
}


Any help would be very much appreciated!

7 Replies

American black bearOP
Hmmm.... Maybe the right solution is to request the data on my Page, but to then implement this filter in a client component that the data is passed to?
I think you're on the right track there. Unless it's a ton of results, filtering in a client component sounds like it'd work great to me. If it is a large list and you want to filter on the server, you could try to use URL parameters for updating on the server side of things
Giant panda
Think of server actions as handlers for POST/PUT requests not special GET requests
As such use search params to filter
And the page can pluck them from the context and adjust the query accordingly
And in using them you don't need special client side handling for filtering other than updating the URL
In addition to links becoming easily shareable