Next.js Discord

Discord Forum

Dynamic filtering using Prisma?

Unanswered
tom_bombadil posted this in #help-forum
Open in Discord
Hey @"use php"
I'm still working on filtering items, so the situation is that with the help of the searchParams() hook, I get the filter values ​​from the URL and put them in some variables.

const filterCategoryParams = searchParams.get("category");
const filterLocationParams = searchParams.get("location");
const filterGenderParams = searchParams.get("gender");
const filterAgeParams = searchParams.get("age");

Now I would have questions for the next step that follows me, and in which way I can apply these filters, that is, in what way I can hit the backend if my fetch function on Prisma looks like this:
  export async function getAdoptPost(context: any) {
  const page = parseInt((context.query.page as string) || "1", 12);
  const pageSize = 12;

  const total = await db.adoptAnimal.count({
  });

  const post = await db.adoptAnimal.findMany({
    skip: (page - 1) * pageSize,
    take: pageSize,
    orderBy: {
      createdAt: "desc",
    },
  });

  return {
    post,
    page,
    pageSize,
    total,
  };
}

page where rendering and want to apply filters:
export default function AdoptPet() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [posts, setPosts] = useState<Post[]>([]);

  // more states..
  const filterCategoryParams = searchParams.get("category");
  const filterLocationParams = searchParams.get("location");
  const filterGenderParams = searchParams.get("gender");
  const filterAgeParams = searchParams.get("age
");

  const fetchData = (page: number) => {
    startTransition(async () => {
      const result = await getAdoptPost(
        {query: { page }});

      setPosts(result.post);
      setPage(result.page);
      setPageSize(result.pageSize);
      setTotal(result.total);
    });
  };

  useEffect(() => {
    const currentPage = parseInt(searchParams.get("page") || "1", 12);
    fetchData(currentPage);
  }, [searchParams]);
{posts.map((animal) => (
...

12 Replies

So If I'm right, you need help with filtering items using prisma, right?
yeah, right that
@tom_bombadil you have where clause
also glad to continue our talking here
yea, I'm looking for it where clause and tried something like this:
export async function getAdoptPost(context: any, category?: string) {
  const page = parseInt((context.query.page as string) || "1", 12);
  const pageSize = 12;

  const total = await db.adoptAnimal.count({
  });

  const post = await db.adoptAnimal.findMany({
    skip: (page - 1) * pageSize,
    take: pageSize,
    where: {
      category: category
    },
    orderBy: {
      createdAt: "desc",
    },
  });

  return {
    post,
    page,
    pageSize,
    total,
  };
}
where: {
      category: category
    },

const fetchData = (page: number) => {
    startTransition(async () => {
      const result = await getAdoptPost({
        query: { page },
        filterCategoryParams,
      });

      setPosts(result.post);
      setPage(result.page);
      setPageSize(result.pageSize);
      setTotal(result.total);
    });
  };

  useEffect(() => {
    const currentPage = parseInt(searchParams.get("page") || "1", 12);

    fetchData(currentPage);
  }, [searchParams]);
?
but in this way, prisma always returns everything from the base, regardless of my filters
model AdoptAnimal {
  id          String   @id @default(auto()) @map("_id") @db.ObjectId
  post_id     String   @map("post_id") @db.ObjectId
  imageUrls   String[]
  location    String
  username    String
  category    String
  petName     String
  vakcinisan  String
  cipovan     String
  pasos       String
  spol        String
  starost     String
  phoneNumber String
  description String

  postId Session @relation(fields: [post_id], references: [id], onDelete: Cascade)

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@map("adoptAnimalPost")
}
this is the Prisma model that I use for this case
if I write like this:
 where: {
      category: {
        contains: "Dog",
      },
    },

it will remove all my animal list from the page, but the total value will still be 9, which is the total number that I render, how to display all the items from the database through this where clause?
And is the point to somehow set a condition in prisma that it displays everything unless one of the filter parameters is sent to it?
@James4u

if I leave it like this:
where: {
      category: category,
    },

it will show all the items from the database, but the filters still don't work, that is, when the input changes, it renders the same 9 items constantly