0

I am pulling an array of objects from an external API. I am taking this array of objects called trails and using .filter() to filter the objects based on a input field, userInput. Here's what the code looks like:

 onChange = (e) => {
   let trails = this.props.trails;
   const userInput = e.currentTarget.value;
   const filteredTrails = trails.filter(
     (obj) => obj.name.toLowerCase().indexOf(userInput.toLowerCase()) > -1);
   console.log(userInput);
   console.log(filteredTrails);
   this.props.searchTrails(this.state.filteredTrails);
   this.setState({
     userInput,
   });
 };

As you can see, I pass filteredTrails as props to the searchTrails method in my App level component. It looks like this:

const searchTrails = (filteredTrails) => {
    setTrails(filteredTrails);
    console.log(filteredTrails);
  };

My issue is that the filter only works one way.

If the user wanted to hit backspace for instance, how do I add trails back to this filteredTrails array of objects?

Thanks in advance!

0

2 Answers 2

1

There is no reverse of "filter", this is why filter doesn't modify the original array, instead it returns a new array. So where your code goes wrong is that you override the "source" with the filtered version. So you'd have to get the full source from your API again which is a waste since it likely didn't change.

Now, I'm guessing that based on the way your app is structured that it's not the same component that does filtering and displaying of the found trails maybe? In either case, don't be afraid to store an extra array of what is currently being displayed.

So your data flow might be:
Get full list from API, store in rawTrails AND filteredTrails (in your App component)
Users types something
Create a subset from rawTrails and store in filteredTrails (use this to display this list or whatever it is you're doing)
User types something else or clears their filter
Set filteredTrails = rawTrails

Another option is to simply filter the raw list on each render (trading memory usage for CPU usage)

Sign up to request clarification or add additional context in comments.

1 Comment

This is so helpful! Thank you!
0

shouldnt you add, filteredTrails without using it from state ?

   this.props.searchTrails(filteredTrails);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.