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

Instructions for passing a JSX code-containing component as a prop to another component

I've developed a base component called Content.js, and instead of creating duplicates with slight modifications each time in my project, I want to reference other components to that base file. I'm wondering if this approach is correct, and how I ...

Obtain information stored locally when an internet connection is established

I'm currently facing an issue with my Local Storage data retrieval process in Vuejs while being online. My ToDo app setup consists of Vuejs, Laravel, and MySQL. When the internet connection is available, I store data in localStorage. The ToDo app has ...

Error in NextJs when trying to display a PDF using react-pdf: MissingPDFException

I am trying to incorporate a PDF file from the public folder into my upcoming application using react-pdf, but I keep encountering an error stating that the PDF cannot be found. Here's how I have set it up: // pdf component import { pdfjs, Document, P ...

Error: The request does not have the 'Access-Control-Allow-Origin' header

As a beginner in post requests, I've been encountering an error when attempting to make a post request. Despite searching for solutions, the answers are too complex for me to grasp how to adjust my code to resolve it. var url = 'http://unturnedb ...

Utilizing diverse values retrieved from HTML data attributes

*UPDATE Within my HTML, I have a list titled "#wordlist" that contains the words for my game, along with corresponding audio and images for each word. Everything is functioning correctly. As there will be multiple versions of the game, I've been tas ...

Top method for organizing an array based on an object's property and displaying the outcome

I encountered a problem for which I couldn't find an immediate solution. I have an array of objects representing products, with each product having a category property. My goal is to group these products by their categories. After some trial and error ...

What is the best way to send an HTTP request in AngularJS to receive data in JSON format?

I am trying to create an AngularJS app that can send HTTP requests for JSON data. I have written the code in my index.html file to request JSON data using AngularJS, but for some reason, the JSON data is not being printed. When I check the console in Fire ...

Different method for adding child elements to the DOM

When creating a DOM element, I am following this process: var imgEle = document.createElement('img');     imgEle.src = imgURL;             x.appendChild(imgEle); Instead of appending the last line which creates multiple img elements ev ...

Don't give up on the entire task just because one promise was rejected

To handle multiple promises in redux saga, you can use the all function (equivalent to Promise.all): yield all( users.map((user) => call(signUser, user)), ); function* signUser() { yield call(someApi); yield put(someSuccessAction); } An issue ...

Extract reference value from an HTML element

Is there a way to access the ref prop from an HTML element using Testing Library React? My current code snippet is as follows: it('element container ref should be null if prop noSwipe is passed', () => { const onCloseMock = jest.fn() ...

Version 13.5 of NextJS is triggering errors in the GraphQL schema

Ever since I updated to NextJS 13.5, I've been encountering these errors specifically when deploying on Vercel (although everything works fine locally): Error: Schema must contain uniquely named types but contains multiple types named "h". at new Gr ...

Query in progress while window is about to close

I'm attempting to trigger a post query when the user exits the page. Here's the code snippet I am currently working with: <script type="text/javascript> window.onbeforeunload = function(){ var used = $('#identifier').val(); ...

The "Overall Quantity" of items will vary as it goes through different numerical values, despite the fact that I employed --

I am currently working on an e-commerce website with a shopping cart feature. The cart displays the number of items added to it, which increases by one when 'Add to Cart' is clicked and decreases by one when 'Remove' is clicked. However ...

Ways to modify the final sum exclusively for a single table

I am currently struggling to figure out how to calculate only the grand total of the first table using just one jQuery/JavaScript script. The code I am referencing is from: Below is the code snippet: <!DOCTYPE html> <html xmlns="http://www.w3 ...

Execute a function on a canvas timer using the setTimeout method

I'm having an issue with my setTimeout function in this code. I want it to call a timer function for a delay, but it's not working consistently every second. Why is that happening? <head> <script> function timer(sec) { var c = do ...

The material UI styled component is not appearing as expected

I'm having trouble getting the MUI styled() utility to apply styles to <MyComponent>Styled div</MyComponent> in my index.jsx file. Any ideas why? import Button from '@mui/material/Button' import Grid from '@mui/mater ...

Encountering a "Module build failed: Error: ENOENT: no such file or directory" issue when attempting to import Material UI

I recently ran into an issue while developing my Next JS app. Everything was smooth sailing until I added material-ui to the project. After adding material-ui, it started throwing this error repeatedly: ./node_modules/@emotion/styled/dist/styled.browser.es ...

The conflict arises when importing between baseUrl and node_modules

I am currently working on a TypeScript project with a specific configuration setup. The partial contents of my tsconfig.json file are as follows: { "compilerOptions": { "module": "commonjs", "baseUrl": &quo ...

Successive promises of catches

Here is a situation that I am dealing with: controller.ts methodA(): void { myServive.someMethod() .then( () => console.log("then") ) .catch( e => { console.log("catch"); }); } service.ts someMethod(): ng: ...

Troubleshooting problem with infinite scrolling in AngularJS with Ionic framework

I recently created a webpage with an infinite scroll page load more script using Ionic AngularJS. However, I encountered an issue where the page restarts from the beginning once it reaches the bottom. Below is the HTML code snippet: <ion-content class ...