monochromaticmau
monochromaticmau

Reputation: 85

Dynamic # of states using for loop and setState . Then need to use states after all have been set

Dynamic number of states. The number of states are dynamic and depends on this mppt number which depends on the user input. I create the states and then after they are all created in the for loop... I'd like to do something with it. I would normally do it in the callback, but I'm using a for loop to create the dynamic number of states. This sets up the defaults and number of elements depending on mppt number. Afterwards, it will be updated by an onChange.

const defaultValues = {
    1:{
        isc: 10.88,
power: 3834.5999999999995,
vmp: 497,
voc: 584.3312579999999,
se: 14,
st: 1,
    },


2: {isc: 9.00,
    power: 3834.5999999999995,
    vmp: 600,
    voc: 584.3312579999999,
    se: 12,
    st: 1},
}

const mppt = 2


.
.
.


   componentDidMount(){
        console.log('Sizing Mounted?')
        for(let i=1 ; i <= mppt ; i++){
            console.log(i)
            this.setState({ [`${i}`] : defaultValues[i]}, ()=>{
                console.log('state been set?')
                console.log(this.state[`${i}`]) //this works
            })
        }
        console.log('Check if state has been checked by here to feed into next function')
        console.log(this.state[`1`])  // undefined

        //This function uses the new set states 
        this.createElementDefaults()  //uses undefined state values

    }

The asyncronous nature of setStates is messing with this. Any suggestions?

Upvotes: 0

Views: 61

Answers (1)

Enchew
Enchew

Reputation: 1001

Try building the object first, set it into the state and then use your funciton in the callback:

  componentDidMount() {
    let s = {};
    for (let i = 1; i <= mppt; i++) {
      s[`${i}`] = defaultValues[i];
    }

    this.setState((prevState) => ({ ...s }), () => {
        console.log(this.state);
        this.createElementDefaults()
    });
  }

Upvotes: 1

Related Questions