J
J
Jedi2018-06-03 06:41:09
React
Jedi, 2018-06-03 06:41:09

The state is not updated, what am I missing?

Hello!
The search only works the first time. Then, when the state should return after filtering, for some reason this does not happen.
Look, please, what could I have missed?
https://jsfiddle.net/anfc4qqj/
Thank you very much in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-06-03
@PHPjedi

The search only works the first time. Then, when the state should return after filtering, for some reason this does not happen.

Yes, it is clear why - when you search, you throw out objects once and for all, there is nothing to return.
Pass the original array of data to props, and filter when looking for it:
class App extends React.Component {
  state = {
    people: this.props.people,
  };

  handeSearch = e => {
    const search = e.target.value.toLowerCase();

    this.setState((state, { people }) => ({
      people: people.filter(n => n.name.toLowerCase().includes(search)),
    }));
  }

  render() {
    return (
      <div className="contacts">
        <input
          type="text"
          className="search-field"
          onChange={this.handeSearch}
        />
        <ul className="contacts-list">
          {this.state.people.map(n => <Person key={n.id} {...n} />)}
        </ul>
      </div>
    );
  }
}

ReactDOM.render(
  <App people={Peoples} />,
  document.getElementById('root')
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question