0

I have a function that looks like this:

select(e) {
    let { selectedItems } = this.state;

    let arr: number[] = [];
    for (var i = 0; i < 2; i++) arr = [...arr, i];

    this.setState(
      {
        selectedItems: arr,
      }
    );
  console.log(selectedItems);
  }

But when I try to console.log(selectedItems), all I get is an empty array. When I console.log(arr), I get the correct output I'm looking for -- an array of length 2. What might be going on here and how can I assign selectedItems to the value of arr?

2
  • Where/when do you log? (I don't understand your sample code.) setState is async. Being an array isn't relevant; setState doesn't care about types. Commented Mar 30, 2020 at 17:30
  • stackoverflow.com/questions/36085726/… Commented Mar 30, 2020 at 17:33

2 Answers 2

1
class A {
  select(e) {
    let { selectedItems } = this.state;
    let arr: number[] = [];
    for (var i = 0; i < 2; i++) arr = [...arr, i];
    this.setState({
      selectedItems: arr
    }, function callback() {
      console.log(this.state) // will have updated value
    });
    console.log(selectedItems); // wont print anything, coz u never assign
    selectedItems = arr;
    console.log(selectedItems); // will have updated value
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, how silly of me, I just realized that this is what I was missing all along
1

setState takes a callback function. Try the following:

  select(e) {
    let { selectedItems } = this.state;

    let arr: number[] = [];
    for (var i = 0; i < 2; i++) arr = [...arr, i];

    this.setState({
      selectedItems: arr,
    }, function(){
        console.log(this.state);
    }.bind(this));
  }


2 Comments

This won't work, you need to bind the this keyword to that callback function.
check the answer below. not binded and appears to work

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.