Skip to content Skip to sidebar Skip to footer

Foreach And Setstate For An Array

I print my existing state like console.log(this.state) I have {'abc-sorted':false, 'def-sorted': 'asc', 'someotherstuff-sorted': true, show: true} What I want to do is set all sta

Solution 1:

Try to generate an object first. Then set your state. This way you will only set it once.

const newState = {};

Object.keys(this.state).forEach(key => {
    if (key.endsWith('sorted')) {
      newState[key] = false;
    }
});

this.setState(newState);

Solution 2:

I hope this can work for you ...

I my case snapshot is the object. Inside my constructor I have

this.state = {
    docs: []
  }

and I did

  snapshot.forEach(function (doc) {
    this.setState({
      docs: [...this.state.docs, doc]
    })
  }.bind(this))

Solution 3:

You can also use Array.prototype.reduce() and prevent immutability in the state:

const state = {
  'abc-sorted': false,
  'def-sorted': 'asc',
  'someotherstuff-sorted': true,
  show: true,
}

constcontainsSorted = key => key.indexOf('-sorted') !== -1const result = Object.keys(state).reduce((prev, curr) => {
  return {
    ...prev,
    [curr]: containsSorted(curr) ? false : state[curr],
  }
}, {})

console.log(result)
// this.setState(result)

Solution 4:

You could instead of calling setState in a loop call it once

const stateUpdates = {};
Object.keys(this.state).filter(o=>{
                return o.endsWith('sorted') 
            }).forEach(o2 => {
                stateUpdates[o2] = false
            })
this.setState(stateUpdates)

Post a Comment for "Foreach And Setstate For An Array"