0

Problem is it possible to add/modify state dynamically if the initial state is empty.

description: actually this tempObj data is coming from the backend as an array of objects , then i modifying the data and assigning it it tempObj and then i want to set it to empty state. so that i can use and modify the data in the application.

what i did : i tried the below code but when i console it , its showing the empty state.

i would really appreciate if some one can help me out with this, thanks

    constructor(props) {
        super(props);
        this.state = {};
      }
      
      componentDidMount() {
      //actually this tempObj data is coming from backend
      //after few loops i am assigning values like this
        let tempObj = {
          132284688949:{3: false, 
                        5: true,
                        6: false},
          262993790438:{3: false,
                        8: true,
                        11: false},
          262993790440:{3: false, 
                        8: true,
                        11: false}};

        this.setState(tempObj);
        console.log(this.state);
      }
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
sravan ganji
  • 4,774
  • 3
  • 25
  • 37

1 Answers1

2

Your information is there. setState is an asynchronous action. Your console.log runs before your state changes. Use your console.log as a callback for setState.

this.setState(tempObj, () => {
  console.log(this.state);
});
Andrew
  • 7,201
  • 5
  • 25
  • 34