1
votes

I currently have a function in react native which does the following:

resetThenSet = (id, arrayId, title) => {
    if(arrayId != 'selectProduct') {
            // Setting state for each selected dropdown in selectedDropdowns
             this.setState({
               dataShowingToggle: true,
               selectedDropdowns: {...this.state.selectedDropdowns, [arrayId]: title}
             }, this.getProductCost(arrayId, id)
           );
}

I run the above and I can confirm arrayId and title variables are valid and contain data. arrayId is also not 'selectProduct'. I added a console.log in there while debugging to ensure it runs, which it indeed does. The expected behavior I would expect is that the state is updated immediately.

However the selectedDropdowns isn't updated in state. When I add: console.log(this.state) after the this.setState update there is no change. If I run the function twice it'll update on the second time it runs.

To test it even further I added static inputs like so:

this.setState({
           dataShowingToggle: true,
           selectedDropdowns: {...this.state.selectedDropdowns, testField: 'me here'}
         }, this.getProductCost(arrayId, id)
       );
       console.log(this.state);

It only update state AFTER the first time it runs. Am I missing something?

UPDATE: I updated the code to run the console.log on the call back to setstate:

  if(arrayId != 'selectProduct') {
    // Setting state for each selected dropdown in selectedDropdowns
    console.log(arrayId + title);
    console.log('i run');
     this.setState({
       dataShowingToggle: true,
       selectedDropdowns: {...this.state.selectedDropdowns, [arrayId]: title}
     }, console.log(this.state)
   );
  };

console.log is 'quantityProduct 25' for the arrayId + title console.log(I run) and then this state is NOT showing the quantityProduct 25

1
What does this.getProductCost do? That function will get called when your state mutation "request" completes.Aaron

1 Answers

3
votes

setState is asynchronous. This is why the function call has an optional callback.

I think you might have other issues.

Try putting that console log inside the callback function when you call setState to see when the state is updated with the values you gave it.