Is there a way to sort search outcomes by a drop-down menu in Next.js?

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?

Answer №1

To properly sort through interviews, make sure to utilize the filterInterviews state variable.

    const filteredInterviews = interviews.filter(interview => {
      if (provinceFilter === 'all') return true;
      return interview.interview.a01_province === filterInterviews)
    }

After filtering, be sure to display the results using filteredInterviews instead of the original interviews.

Answer №2

I finally found the solution.

I made the mistake of trying to compare a string select value to a number.

To fix this, I converted the drop-down event value e.target.value to an integer using parseInt(e.target.value), and then used the filter function to match it with the province code from the database.

  const handleProvinceFilter = (e) => {
    setProvinceFilter(parseInt(e.target.value));
  };

  const filteredInterviews = interviews.filter(
    (interview) => interview.a01_province === provinceFilter
  );


Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is the type of parameter 1 not an 'HTMLFormElement', causing the failure to construct 'FormData'?

When I try to execute the code, I encounter a JavaScript error. My objective is to store the data from the form. Error Message TypeError: Failed to create 'FormData': argument 1 is not an instance of 'HTMLFormElement'. The issue arise ...

How can I load data into Vuex store before the application starts?

Within the created hook of App.vue, I am initiating a dispatch call to my store. Subsequently, in a child component, I attempt to retrieve this data using a getter. However, an issue arises as the child component is loaded before the data is stored, causin ...

``on click of the back button of the browser, automatically submit the form

I'm facing a specific issue that I need help with. I have created a form with a hidden value, and I want it to be submitted when the user clicks the browser's back button. Although I've managed to control the backspace key, I haven't be ...

The use of `await` within a loop may not function as anticipated when the code is being run through Puppeteer, yet it functions flawlessly when executed in the browser's console

Currently, I am assessing the functionality of the codeToBeEvaluated function within a browser environment using puppeteer. Within codeToBeEvaluated, there is a while loop designed to trigger an alert (referenced as LINE B) every 10 seconds. The issue ari ...

Having trouble removing just one element from an array in Redux. Any suggestions on how to make it work properly?

I'm currently working on creating a dynamic algorithm for removing an item from an array. Reducer: import { LOAD_PAGES, REMOVE_PAGE } from "./dynamicMenuActions"; export const initialState = { pages: [] }; export const dynamicMenuReducer = (state ...

Exploring the capabilities of the Express router and its various methods

I am curious about var server = http.createServer(function(req, res) { // something } server.listen(3000); Is the server created and listening on port 3000 immediately after running this code block, or is it only created at first and then started ...

The form action seems to be unresponsive when utilized within a vue-bootstrap form

I'm utilizing a form submission service called formsubmit.co, which allows forms to receive input data via email without the need to develop a backend for storing and transmitting data. Formsubmit handles all the storage and sending processes. Accordi ...

Ways to stop VoiceOver from selecting the background content when a modal is open

Is there a way to prevent VoiceOver from reading the content behind a modal? I tried using aria-modal=true, but it seems VoiceOver does not support this feature by default like NVDA and JAWS do. I found more information about this on . According to the in ...

Issue: Unable to open port (GetCommState) : Error code 1 not recognized - Utilizing Nodejs, express, SerialPort

I am currently attempting to establish a connection between a fiscal printer with serial input and nodejs. I am utilizing the SerialPort module, but encountering difficulty in establishing the connection. The console is displaying the following error messa ...

Transferring a zipped file between a Node.js server and a Node.js client

I am facing an issue with sending a zip file from a node.js server to a node.js client. The problem is that when I try to save the zip file, it becomes corrupted and cannot be opened. To create and send the zip file to the client, I am using the adm-zip l ...

Utilizing Django models to populate Google Charts with data

I am currently working on showcasing charts that display the most popular items in our store. To achieve this, I need to extract data from the database and incorporate it into the HTML. Unfortunately, the charts are not loading as expected. When testing wi ...

Catalog of items in Mustache

I am currently working on generating HTML content using the mustache template engine. However, I have encountered an issue when trying to render a list of objects. Below is an example of my object: var Prod={ "Object1": { "name": "name1", "cat ...

The JSON.Parse function in Google Apps Script is leading to a 'server connection error' message during debugging

I'm not a professional developer, but I do code occasionally. Currently, I am working on some Apps Script code to interact with an API and store the data in SQL. Most of it is working fine, but I have encountered an issue while debugging in the Apps S ...

Struggling to implement a Datepicker in the date column of a table created using HTML and JavaScript

I am encountering an issue while creating a table in html and javascript. I am unable to use a Datepicker in the date column when inserting a new row, even though it works fine when using in normal html code. Below is the javascript function: //Script fo ...

What is the best way to prevent labels from floating to the top when in focus?

How can I prevent the label from floating on top when focusing on a date picker using Material UI? I have tried several methods but nothing seems to work. I attempted using InputLabelProps={{ shrink: false }} but it did not resolve the issue. Here is a li ...

Accessing dynamically created AJAX controls in ASP.NET during postback operations

I am dynamically creating 2 dropdown boxes and a CheckBoxList control using AJAX callbacks to a web service (.asmx file). The server-side service generates the Dropdowns and CheckBoxList, returning the rendered html as a string which is then inserted into ...

Creating dynamic templates for table rows in AngularJS directives

Is it possible to dynamically load an AngularJS Directive templateUrl while working within a table? In my scenario, I have the following HTML structure where I am repeating a tr element with a fw-rule directive: <tbody> <tr ng-repeat="rule in ...

Choosing various li classes within a navigation bar

Struggling to pick the right JQuery elements for my portfolio site. The aim is to show/hide the .inner (Task) items by clicking on the .outer (Category) items, complete with rotating .arrows when the menu expands. Check out a similar question, along with ...

What methods are available to load sections of a complex SVG shape asynchronously?

I'm currently in the process of creating a website with a geographic map built using SVG, pulling data from OpenStreetMap. Due to its large size and potential for transformations such as zooming and moving, only a portion of it will be visible on the ...

Using the PUT method in combination with express and sequelize

I am having trouble using the PUT method to update data based on req.params.id. My approach involves retrieving data by id, displaying it in a table format, allowing users to make changes, and then updating the database with the new values. Here is the co ...