What is the best way to navigate through this array within my nextjs/typescript/fetch application?

Having trouble finding a way to efficiently search through the CustomersList array. Any help would be greatly appreciated.

Here's what happens after fetching the data:

const data = await res.json();
  return {
    props: {
      CustomersList: data,
    }
  };

This is how I'm displaying the data on the page:

<ul className="customers">
          {CustomersList.map((customer) => (
            <form method="POST" action={AppendUrl(customer.Id)}>
              <table className="customer-list">
                <tr>
                  <th>Customer Name:</th>
                  <th>Customer Id:</th>
                </tr>
                <tr>
                  <td>{customer.Name}</td>
                  <td>{customer.Id}</td>
                  <input type="submit" value="Select"/>
                </tr>
              </table>
            </form>
          ))}
        </ul>

I am interested in adding a search bar that allows users to search for customers by name (customer.Name).

Answer №1

I stumbled upon some code that proved to be incredibly useful.

search code:

//Search Customer
  const [name, setName] = useState("");
  const [foundCustomers, setFoundCustomers] = useState(CustomersList);

  const filter = (e: { target: { value: any } }) => {
    const keyword = e.target.value;

    if (keyword !== "") {
      const results = CustomersList.filter((customer) => {
        return customer.Name.toLowerCase().startsWith(keyword.toLowerCase());
        // Use the toLowerCase() method to make it case-insensitive
      });
      setFoundCustomers(results);
    } else {
      setFoundCustomers(CustomersList);
      // If the text field is empty, show all users
    }

    setName(keyword);
  };

searchbox input code:

<ul className="customers">
        <input
          type="search"
          value={name}
          onChange={filter}
          className="input"
          placeholder="Customer Name"
        />
        {foundCustomers && foundCustomers.length > 0 ? (
          foundCustomers.map((customer) => (
            <form method="POST" action={AppendUrl(customer.Id)}>
              <table className="customer-list">
                <>
                  <tr>
                    <th>Customer Name:</th>
                    <th>Customer Id:</th>
                  </tr>
                  <tr>
                    <td>{customer.Name}</td>
                    <td>{customer.Id}</td>
                    <input type="submit" value="Select" />
                  </tr>
                </>
              </table>
            </form>
          ))
        ) : (
          <h1>No results found!</h1>
        )}
      </ul>

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

What is the best way to restrict a React input field to have values within the minimum and maximum limits set by its

As a newcomer to React, I am working on restricting my input to values between -10 and 10. Currently, the input is set up to accept any value, and I am utilizing hooks like useState and useEffect to dynamically change and set the input value. My goal is ...

Enhance the step implementation in Cucumber-js

Background In my TypeScript project, I am utilizing https://github.com/cucumber/cucumber-js. The code snippet below showcases a typical cucumber implementation: import { Given, Then, When } from 'cucumber' Given(`Page is up and run ...

Encountering an Issue: The formGroup function requires an instance of a FormGroup. Kindly provide one

I am a beginner with Angular 2 and despite reviewing numerous stack overflow answers, I still can't resolve my issue. I have recently started learning about angular reactive forms and wanted to try out my first example but I'm facing some diffic ...

Is it possible to configure MongoDB to function with Vercel's Edge Serverless Functions?

My API on Vercel Serverless Functions is causing long cold start times when creating new documents. In order to improve request speed, I'm considering running the API on Vercel Edge Functions. However, I have encountered an issue as the edge runtime d ...

Issue with TranslateModule Configuration malfunctioning

I have put together a file specifically for managing ngx-translate configuration: import { Http } from '@angular/http'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { TranslateLoader, TranslateModu ...

Struggling to accurately convert the string into a date object

I have an array of objects structured like this: const days = [ { _id: 12312323, date : '30/12/2021', dateStatus : 'presence' }, ... ] I am looking to convert the date property from a string to a Date object using the follo ...

Unable to change the data type of the value within the object

I have developed a next.js application that uses MongoDB as the database. In my code, I am facing an issue where after clicking the submit button, all the data is displayed in a table. I have extracted specific data like product_unit and product_price sep ...

If an interface property is set as (), what significance does it hold?

While exploring the Vue.js source code located at packages/reactivity/src/effects.ts, I came across this snippet: export interface ReactiveEffectRunner<T = any> { (): T effect: ReactiveEffect } I'm curious, what does () signify in the code ...

Encountering Error 500 while making a POST request in the Next JS 13 application folder

While attempting to create a user through a simple route, I encountered an error message: 500 Internal Server Error. The logs indicate: error TypeError: res.status is not a function at POST (webpack-internal:///(rsc)/./app/api/register/route.ts:33:20 ...

Rewriting Next.js with custom headers

My web app allows users to create their own profiles with custom usernames, which can be accessed via the following URLs. ourplatform.com/john ourplatform.com/john/about ourplatform.com/john/contact ourplatform.com/jane ourplatform.com/jane/about ourplatf ...

Angular authentication guard does not redirect properly after returning a Promise<UrlTree>

My authentication guard is set up to control access to the /sign-in and /verify-email routes, allowing only users who are not logged in or have not verified their email: export const signInGuard: CanActivateFn = (activatedRouteSnapshot: ActivatedRouteSnap ...

Guide to handling disabled dates in the react-date-range component

I am seeking guidance on how to handle disabled dates that are not included in the availableDates state. This feature is crucial for booking travel. 'use client'; import axios from 'axios'; import { useEffect, useState } from 'rea ...

Double Calling of Angular Subscription

I am currently working with a series of observables that operate in the following sequence: getStyles() --> getPrices() Whenever a config.id is present in the configs array, getStyles() retrieves a style Object for it. This style Object is then passed ...

Issue: The content of the text does not align with the HTML generated by the server

I'm struggling with an algorithm in next.js and encountering hydration errors. Here is the code I am using: import numbers from "../../functions/numberGenerators.js" export default function test() { ...

Different TypeScript parameters that cannot be used together

Consider the given JavaScript function below: function x({foo, fooId, bar, barId}) {} I am looking to refactor this function into TypeScript in such a way that the caller is required to provide either foo or fooId, but not both. The same rule should apply ...

Straightforward npm package importing syntax

I am looking for a way to simplify the import statements when publishing a new TypeScript package on npm. Ideally, I would like to be able to use something like: import { FirstClass, SecondClass } from "my-repo"; However, currently I have to use longer i ...

Sending input in a nested event listener

I am currently utilizing Highcharts for the purpose of showcasing an interactive map with custom countries. I have a specific requirement to enable the drilldown functionality, which involves clicking on a country to zoom in on another map displaying inter ...

Angular 9 Issue: Failure to Display Nested Mat-Tree Children

Hello everyone, I'm new to posting questions on Stack Overflow and I'm seeking some assistance with an issue I'm having with Mat-Tree. Despite the fact that my data is present when I console log it, the children are not appearing. I am fetc ...

When utilizing custom ngDoBootstrap and createCustomElement in Angular, the router fails to recognize the URL being used

WHEN I implement a custom ngDoBootstrap function instead of the default bootstrap: [AppComponent] like shown below: @NgModule({ imports: [ BrowserModule, FormsModule, AppRoutingModule ], declarations: [ AppComponent, HelloComponent ], exports: ...