Problem while filtering in React

Problem while filtering in React
0

#1

Hi,

I am new to React and I am trying to make a simple app with the concepts I learned.
I have created some counters components and I would like to search by their names.
The issue I am trying to solve is that ‘this.setState’ doesn’t reflect to changes as ‘console.log’. (Please, check out my idea and code below.)

Thank you,
Enric

// App.js
          <Counters
            counters={this.state.counters}
            onSearch={this.handleSearch}
          />
// Counters.js
          <input
            type="search"
            onInput={this.props.onSearch}
            placeholder="Search Counter..."
          />
// App.js
  handleSearch = e => {
    const counters = this.state.counters.filter(counter =>
      ("counter #" + counter.id).includes(
        e.target.value.trim().toLowerCase()
      )
    );

    console.log(counters); // logs the correct result
    // this.setState({ counters }); 
  };

#2

Link to entire app if possible


#3

Sure @EddieCornelious.
Here is the link to the source code: https://transfernow.net/714nn3z1ecii


#4

I was looking for a codepen. not looking to download anything.


#5

@EddieCornelious I created a GitHub repository: https://github.com/enric1/simple-react-app


#6

You will get a lot more responses and help if you put your project up on something Codepen, JSFiddle, or CodeSandBox. Putting your stuff on Github is great for collaboration, but if someone just wants to give you some help, they do not want to have to download and install anything.


#7

Can you explain how to reproduce the issue you are having making sure to explain what you are seeing in the console vs what you expect to see on the page when you do something in particular?


#8

What you have above which is commented out is not the same as what you have in your github code. In the commented code of github, you have:

    console.log(counters); // logs the correct result
    // this.setState(
    //   counters
    // );

If you use the code you original posted on the forum here and uncomment the line:

    // this.setState({ counters }); 

I believe you will get the result you want. If you uncomment the lines on github, you will not get the correct filter, because you forgot to wrap counters in { and }. setState accepts an object with property/value pairs and not an array (which is what you passed).