Aims.kar
Aims.kar

Reputation: 151

How to fill a specific state with a dynamic key?

I have an empty state that is filled using a JavaScript object as follows:


  constructor(props) {
    super(props);
    this.state = {}
  }

  initialStateSet = (model) => {
    model.map(m => this.setState({ [m.key]: null 
   }))
  }

I want to create a specific state and fill that with those values instead something like:

  constructor(props) {
    super(props);

    this.state = {
      EmptyList: {}
    }
  }

initialStateSet = (model) => {
    model.map(m => this.setState({ EmptyList:  {[m.key]: null } } )
  }

Unfortunately its only filling in the last value and not all the values from the object like I want

Upvotes: 1

Views: 68

Answers (2)

Yousaf
Yousaf

Reputation: 29282

There are 2 ways you can do this:

  1. use previous state

    initialStateSet = (model) => {
       model.map(m => {
          this.setState(prev => ({ EmptyList:  { ...prev.EmptyList, [m.key]: null } }))
       });
    }
    
  2. first create the list and then update the state

    initialStateSet = (model) => {
        const list = model.map(m =>  ({[m.key]: null }))
        this.setState({ EmptyList: list });
    }
    

if you use 2nd method, then EmptyList will be an array. If you want EmptyList to be an object, then do this:

initialStateSet = (model) => {
      const obj = {};
      model.forEach(m =>  obj[m.key] = null);

      this.setState({ EmptyList: obj });
} 

Upvotes: 1

Vivek Doshi
Vivek Doshi

Reputation: 58533

Issue :

// issue with this is, it always update `EmptyList` with next value
// you are assigning a new object to `EmptyList` everytime instead appending
// so as result, you will always get the last one
model.map(m => this.setState({ EmptyList:  {[m.key]: null } } )

Solution :

I think, this is what you want is :

const list = {};
model.forEach(m => { list[m.kye] = null })

// instead o updating state in loop
// you should update the state only once, this is more preferable,
this.setState({ EmptyList : list });

Upvotes: 2

Related Questions