How To filter many times from the initial State in React

Related searches

let Say I want to filter results from the give user array inside the initial state

constructor(props) {
    super(props);
    this.state = {
      users: [
        {
          id: 1,
          name: "Gray",
          phonenumber: 12342,
          brand: "Honda",
          age: "12",
          occupation: "teacher",
          state: "pending"
        },
        {
          id: 2,
          name: "Ker",
          phonenumber: 12342,
          brand: "Honda",
          age: "22",
          occupation: "Lover",
          state: "active"
        },
        {
          id: 3,
          name: "Kite",
          phonenumber: 12342,
          brand: "Honda",
          age: "2",
          occupation: "monkey",
          state: "active"
        },
        {
          id: 4,
          name: "Money",
          phonenumber: 12342,
          brand: "Honda",
          age: "2",
          occupation: "monkey",
          state: "active"
        },
        {
          id: 5,
          name: "ajnkaef",
          phonenumber: 12342,
          brand: "Honda",
          age: "2",
          occupation: "monkey",
          state: "passive"
        },
        {
          id: 6,
          name: "awfehuawe",
          phonenumber: 12342,
          brand: "Honda",
          age: "2",
          occupation: "monkey",
          state: "active"
        }
      ]
    };

So I write 2 functions That finds for pending state and active state

findActive() {
    let activeusers = this.state.users.filter(user => {
        if(user.state === 'active'){
            // console.log(user)
           return user
        }
    })
    this.setState({
        users: activeusers
    })
  }

  findPending(){
    let pendingUsers = this.state.users.filter(user => {
        if(user.state === 'pending'){
            // console.log(user)
           return user
        }
    })
    this.setState({
        users: pendingUsers
    })
  }

Then I passed these 2 functions as props into a component. The program is running fine if I want to filter 1 time only. But When I filter for the second time the results will be empty always. Because after the first filter I always set the state to the new Array.

Can someone help me find the good solution for this problems.


I'm trying to understand your question I don't know if I get it right. But you can use the code below if you want to filter a pending or active state of the user. I also write the callback just in case you need to call a function after you call the setState.

this.setState(prevState=>{
   return {
    users: prevState.users.filter(user => user.state == 'active' || user.status == 'pending')
   }
}, ()=> { 
  //callback here. You can place another setState or anything here.
});

How to manage React State with Arrays, Often the answer is to grab a fundamental JavaScript function that does the job for you As mentioned, the initial array state is done in the React component's When it comes to removing an item from an array, the array filter� React: Initial Thoughts. React is a front end JavaScript framework written by the good folks at Facebook. I've been working in React for a few weeks now and I am beginning to really appreciate it. One piece that I like a lot is the idea that React Components have state, which makes the whole process of building a front end feel more object


If you want filter all the active and pending use:

 findActiveOrPending() {
    let users = this.state.users.filter(user => {
       if(user.state === 'active' || user.state === 'pending'){
           return user
        }
    })
    this.setState({
        users: users
    })
}

if you want you the exist functions for that, makr the function to return a list of users instead set state inside the function, like this:

findActive() {
    return this.state.users.filter(user => {
       if(user.state === 'active'){
           return user
        }
    })
}

findPending(){
    return this.state.users.filter(user => {
       if(user.state === 'pending'){
           return user
        }
    })

}

then for active

this.setState({users: findActive()})

for pending

this.setState({users: findPending()})

for both

this.setState({users: [...findActive(), ...findPending()]})

Stacking filters on a state and reverting back to initial state, Issue I am facing is how can I stack filters on the displayed results which I that then size etc and each filter reduces the number of displayed results but basically takes the initial state and apply whatever filter was used on it� Thanks to the setState() call, React knows the state has changed, and calls the render() method again to learn what should be on the screen. This time, this.state.date in the render() method will be different, and so the render output will include the updated time. React updates the DOM accordingly.


findActive() {
    let activeUsers = this.state.users.filter(user => {
        if(user.state === 'active'){
            // console.log(user)
           return user
        }
    })
    this.setState({
        activeUsers
    })
  }

  findPending(){
    let pendingUsers = this.state.users.filter(user => {
        if(user.state === 'pending'){
            // console.log(user)
           return user
        }
    });
    this.state.pendingUsers = pendingUsers; //this will not re-render component and yet you will get filtered pending users data in this. Option 2
    this.setState({
        pendingUsers
    })
  }

You can use different state to store those values if you have to show updated active or pending users in the UI as state will be updated and re-render will happen to change the UI.

Or you can store filtered data locally just for your reference(Option 2).

Also you can use prevState as Mart Macion described.

Thinking in React – React, Since you're often displaying a JSON data model to a user, you'll find that if your model ProductTable (green): displays and filters the data collection based on user input The original list of products is passed in as props, so that's not state. We will build a React Application that has input text to look up for filtering items. The filter works and updates every time we type in the textbox. Filter list with input text Context. Remember that our App state is like this:


It's obvious that you are doing it wrong.

you have a state(users), and when you are calling filter on itself(users) you are modifying the original array itself. what you can do is declare another variables in the state and assign the filtered values to those variables instead of modifying the original one. either way you are not suppose to touch the original one to preserve the integrity.

    this.state = {
     users: [your data],
     pendingUsers: [],
     activeUsers: [],
    }

    findActive() {
     const { users } = this.state
     this.setState(prevState => ({
      ...prevState,
      activeUsers: users.filter(item => item.state === 'active'),
     }))    
    }

  findPending(){
   const { users } = this.state
   this.setState(prevState => ({
    ...prevState,
    pendingUsers: users.filter(item => item.state === 'pending'),    
   }))
  }

  render() {
   const { users, activeUsers, pendingUsers } = this.state

   return <ChildComponent {...{ users, activeUsers, pendingUsers }} />
  }

Building Your Own Hooks – React, They let you use state and other React features without writing a class. Its name should always start with use so that you can tell at a glance that the rules of And as we learned earlier, we can call useState and useEffect many times in one� Example. There are changes in how we are setting the initial states. React.createClass. We have a getInitialState function, which simply returns an Object of initial states.


21 Performance Optimization Techniques for React Apps, For handling changes to state or props in React components, we can We often need to pass initial data with props to the React component to set the like image processing, sorting, filtering, and other CPU extensive tasks. The only time we are allowed to define the state explicitly is in the constructor to provide the initial state. React is highly efficient and thus uses asynchronous state updates i.e. React may update multiple setState() updates in a single go. Thus using the value of current state may not always generate the desired result.


First, we should create component to display movies list. Note, this is a pure stateless component, we are not making sorting or filtering there, just rendering derived props:


In my last post I discussed React’s controlled components and how you might set up a filter form. This week I’m going to show you how to setup the filter for the results. This component takes