I am currently working on implementing a filter for my data based on selections made in a drop-down menu.
Here's the setup:
I have MSSQL data being pulled into NextJS using Prisma (ORM). My goal is to create a dropdown filter that will refine the displayed results according to the user's selection.
This is what I've accomplished so far:
/checkin/index.js
import Head from "next/head";
import { PrismaClient } from "@prisma/client";
import { NavBar } from "../../components/Layouts/NavBar";
import provs from "../../assets/prov.json";
import { useState } from "react";
const prisma = new PrismaClient();
export async function getServerSideProps() {
const interviews = await prisma.sdesmain.findMany();
return {
props: { interviews },
};
}
export default function Checkin({ interviews }) {
const [provinceFilter, setProvinceFilter] = useState();
const [filterInterviews, setFilterInterviews] = useState(interviews);
const handleProvinceFilter = (e) => {
const provCode = e.target.value;
setProvinceFilter(provCode);
if (provCode === "all") {
setFilterInterviews(interviews);
}
};
const filteredInterviews = filterInterviews.filter((interview) => {
if (interview.a01_province === provinceFilter) {
return interview;
}
});
return (
<div>
<NavBar />
<div className="container mx-auto">
<div>
<h1 className="text-3xl font-bold">Showing Interviews</h1>
</div>
<div className="flex flex-col py-6">
<select
className="bg-gray-200 rounded-md p-2 max-w-md"
onChange={handleProvinceFilter}
>
<option value="all">All</option>
{provs.map((prov) => (
<option value={prov.id} key={prov.id}>
{prov.provinceName}
</option>
))}
</select>
</div>
</div>
<div className="container mx-auto">
<h1>Filtered Interviews List</h1>
<div className="overflow-x-auto relative ">
<table className="table-auto w-full text-sm text-left text-gray-800 dark:text-gray-800 ">
<thead>
<tr>
<th>Province Code</th>
<th>Cluster Number</th>
<th>Household Sample Number</th>
</tr>
</thead>
<tbody>
{filterInterviews.map((interview) => (
<tr key={interview.interview_key}>
<td>{interview.a01_province}</td>
<td>{interview.a02_clusterNumber}</td>
<td>{interview.a06_hhsampleNumber}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
);
}
The data is currently displayed without the intended filtering based on the drop-down selection. https://i.stack.imgur.com/GIpaS.png
How can I ensure the filtering functionality works as expected?