What steps should I follow to incorporate this filter into my code?

Currently, I am working with a list of names obtained from an array using the Fetch method. I have implemented a searchHandler method which is triggered by a button click, and it logs the input data in the console:
https://codesandbox.io/s/jovial-lovelace-z659k
However, I am facing an issue where I want to enter a specific "First name" in the input field, click the button, and only display the line corresponding to that name. Unfortunately, I am struggling to implement the necessary filter logic.
I came across a potential solution online, but I am unable to seamlessly integrate it into my existing code. Here's the snippet:

getFilteredData() {
    if (!this.state.search){
        return this.state.data
    }
    return this.state.data.filter(item=>{
        return item["firstName"].toLowerCase().includes(this.state.search.toLowerCase())
    });
}

Can you guide me on how to incorporate this filter logic into my code? What modifications should I make in the render method?

Answer №1

Your current approach seems to be on the right track. Below is the revised code with comments detailing the modifications:

searchHandler = search => {
    // Checking if the search query is empty and resetting data to display the initial list
    if (search) {
        const arr = this.state.data.group && this.state.data.group.first ? this.state.data.group.first : this.state.data;
        const filteredArr = arr.filter((item) => {
            // Filtering based on 'search' instead of 'state.search' as the state has not been updated with the search term
            return item["firstName"].toLowerCase().includes(search.toLowerCase())
        })
        // Updating state to reflect filtered data
        this.setState({data: filteredArr})
    } else {
        this.resetData();
    }
};

// Asynchronous function to reset data, similar to what is in componentDidMount
async resetData() {
    const response = await fetch("/data/mass.json");
    const data = await response.json();
    this.setState({
        data
    });
}

Note:

includes may not be supported by all browsers. For a more reliable solution, consider using indexOf. More information can be found here.

Answer №2

If your fetched data consists of an array of objects and you need to filter out objects that meet certain criteria, here is a guide on how to create a search handler:

searchHandler = searchTerm => {
    const { data } = this.state;
    const filteredData = {
      group: {
        first: Object.values(data.group.first).filter(item => item.firstName.includes(searchTerm)),
      }
    }
    this.setState({ data: filteredData });
};

This function takes the array of objects from the data and filters out only those objects that contain the specified search term in their firstName property. The filtered array of objects is then structured the same way as the original data object and updated in the state. You do not need to modify the render method as it already works with the data in the state. When a search is made, the state is updated and the new data will be reflected in the render.

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

Unable to modify array state with data from another state

Two state objects are at play here. The first is personnel, which consists of an array of 1-object arrays structured like this: [[{}],[{}],[{}],[{}],...]. The second state object is rowItems, where the goal is to extract all objects from the inner arrays o ...

What is the best way to send a POST request with axios in a React application?

Having trouble with the axios post request. When I press the Button, nothing seems to happen. Supposedly, the data I input into the fields should be submitted to the API. However, there's no redirection or any indication that the submission is success ...

I am experiencing an issue where the req.body object is returning undefined even after implementing express router and using express.urlencoded

Below is the code from my server.js file: const express = require("express"); const articleRouter = require("./routes/articles"); const app = express(); app.set("view engine", "ejs"); app.use("/articles", ...

How can I interact with objects in a Three.js scene? Is document.getElementById() the appropriate method to use?

for ( var j = 0; j < 100; j ++ ) { var particles = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: 0x666666, program: programStroke } ) ); particles.position.x = Math.random() * 800 - 400; particles.position.y = Math.random() ...

Transfer the "file" from the busboy to the GM for FTP uploading

I'm looking to resize an uploaded image using nodejs and send it via ftp. I'll be utilizing nodejs, busboy, GraphicsMagick, and jsftp. var uploadFile = function(dir, req, cb) { req.busboy.on('file', function(fieldname, file, filename, ...

Monitoring changes to localstorage in AngularJS

How can I monitor changes to localStorage using $watch? I have created a factory to simplify setting and getting values .factory('$localstorage', ['$window', function($window) { return { set: function(key, value) { ...

Ways to remove a JSON item based on its index position?

In my JSON object, I am trying to find a way to remove the first element. Here is an example of what I have: var obj1 = {property:'something', does:'somethingElse', is:'somethingCool'}; var obj2 = {does:'somethingElse&ap ...

The tooltips on a resized jQuery Flot chart are displaying in the incorrect location

Currently, I am utilizing the flot library for my chart. I am facing an issue with getting the correct tooltips to display when I scale the chart using this CSS rule: transform: scale(0.7); The flot source relies on the function findNearbyItem to locate ...

Three.js: transforming textures into data textures

Currently, my goal is to create a delayed webcam viewer using javascript, utilizing Three.js for its WebGL capabilities. At the moment, I am able to capture frames from the webcam and display them after a specified time interval using canvas and getImageD ...

Angular 2 Aot Issue: CRITICAL ERROR: CALL_AND_RETRY_LAST Allocation unsuccessful - JavaScript heap exhausted

Encountered an issue while running Angular 2 AOT rollup: <--- Last few GCs ---> 144518 ms: Mark-sweep 1317.0 (1404.4) -> 1317.0 (1404.4) MB, 1522.9 / 0.0 ms [allocation failure] [GC in old space requested]. 146029 ms: Mark-sweep 1317.0 (1404 ...

Encountering a connection error when trying to access a Google spreadsheet within a Next.js application

I am currently exploring Next.js and attempting to utilize Google Sheets as a database for my project. Although my application is functioning correctly, there is still an error message displaying that says "not forgot to setup environment variable". I have ...

sophisticated method for sorting through data within an array of arrays

How can data be filtered from an array of arrays? Below is an example to help explain the process. To filter the data, use startnumber and endnumber in the query. const data = [ { "name": "x", "points": [ [100, 50, 1], //[number, value ...

Designing the database structure for a Q&A website powered by MongoDB

Looking for some assistance as I embark on creating a website similar to Yahoo Answers or StackOverflow (in a different category with no competition). My main hurdle right now is figuring out the best approach to structuring the database for user and quest ...

The Angular application sent an OPTIONS request instead of a POST request via HTTP

I'm encountering CORS errors while attempting to send HTTP requests from my angular.js application to my server. The code used to make the HTTP request is as follows: functions.test = function(foo, bar) { return $http({ method: 'POS ...

Preventing the addition of hash tags to the URL by the anything slider

Why does the Anything Slider add hash tags like #&panel1-1 to the end of the URL? I attempted using hashtags:false but it was unsuccessful. Are there alternative methods to prevent it from creating these hashtags? ...

What is the best way to use an ID to call a Class in a Script?

Here is the current code I have: <script> window.addEventListener("load", function() { document.getElementsByClassName("but")[0].addEventListener("click", function(e) { // e.preventDefault(); // if it i ...

What is the proper way to integrate "require" into my Angular 2 project?

Currently, I am still in the process of trying to integrate the angular 2 code mirror module into my angular 2 application. Previously, I faced some challenges with imports which I discussed in detail here, and managed to overcome them. However, a new iss ...

"Converting an image in Byte[] format to a Base64 string in JavaScript: A step-by-step

Can anyone help me figure out how to convert an image from an SQL database into a Base64 string? The image is currently in the format {byte[6317]}. ...

Transformation in input value does not manifest in other components

When adjusting the sliders, the input fields are supposed to update accordingly. However, I've noticed that the changes in the input fields only take effect if I manually change their values. The automatic reflection doesn't seem to occur when us ...

Combining two observable entities

Utilizing Angular 4 and rxjs, the objective is to fetch data from two distinct servers in JSON format, merge this data, and exhibit it in a list by associating the list with an observable array. **Word Search Component TypeScript File:** @Component( ...