score:27

Accepted answer

That's because the response from chrome.runtime.sendMessage is asynchronous; here's the order of operations:

var newDeals = [];

// (1) first chrome.runtime.sendMessage is called, and *registers a callback*
// so that when the data comes back *in the future*
// the function will be called
chrome.runtime.sendMessage({...}, function(deals) {
  // (3) sometime in the future, this function runs,
  // but it's too late
  newDeals = deals;
});

// (2) this is called immediately, `newDeals` is an empty array
this.setState({ deals: newDeals });

When you pause the script with the debugger, you're giving the extension time to call the callback; by the time you continue, the data has arrived and it appears to work.

To fix, you want to do the setState call after the data comes back from the Chrome extension:

var newDeals = [];

// (1) first chrome.runtime.sendMessage is called, and *registers a callback*
// so that when the data comes back *in the future*
// the function will be called
chrome.runtime.sendMessage({...}, function(deals) {
  // (2) sometime in the future, this function runs
  newDeals = deals;

  // (3) now you can call `setState` with the data
  this.setState({ deals: newDeals });
}.bind(this)); // Don't forget to bind(this) (or use an arrow function)

[Edit]

If this doesn't work for you, check out the other answers on this question, which explain other reasons your component might not be updating.

score:0

After looking into many answers (most of them are correct for their scenarios) and none of them fix my problem I realized that my case is a bit different:

In my weird scenario my component was being rendered inside the state and therefore couldn't be updated. Below is a simple example:

constructor() {
    this.myMethod = this.myMethod.bind(this);
    this.changeTitle = this.changeTitle.bind(this);

    this.myMethod();
}

changeTitle() {
    this.setState({title: 'I will never get updated!!'});
}

myMethod() {
    this.setState({body: <div>{this.state.title}</div>});
}

render() {
    return <>
        {this.state.body}
        <Button onclick={() => this.changeTitle()}>Change Title!</Button>
    </>
}

After refactoring the code to not render the body from state it worked fine :)

score:1

I was going through same issue in React-Native where API response & reject weren't updating states

apiCall().then(function(resp) { this.setState({data: resp}) // wasn't updating }

I solved the problem by changing function with the arrow function

apiCall().then((resp) => {
    this.setState({data: resp}) // rendering the view as expected
}

For me, it was a binding issue. Using arrow functions solved it because arrow function doesn't create its's own this, its always bounded to its outer context where it comes from

score:2

My issue was that I was using 'React.PureComponent' when I should have been using 'React.Component'.

score:2

I was updating and returning the same object passed to my reducer. I fixed this by making a copy of the element just before returning the state object like this.

Object.assign({}, state)

score:2

To update properly the state, you shouldn't mutate the array. You need to create a copy of the array and then set the state with the copied array.

const [deals, setDeals] = useState([]);
    
   function updateDeals(deal) {
      const newDeals = [...deals]; // spreading operator which doesn't mutate the array and returns new array
      newDeals.push(deal);

      // const newDeals = deals.concat(deal); // concat merges the passed value to the array and return a new array
      // const newDeals = [...deals, deal] // directly passing the new value and we don't need to use push
    
      setDeals(newDeals);
    }

score:10

In my case, I was calling this.setState({}) correctly, but I my function wasn't bound to this, so it wasn't working. Adding .bind(this) to the function call or doing this.foo = this.foo.bind(this) in the constructor fixed it.

score:18

Another oh-so-easy mistake, which was the source of the problem for me: I’d written my own shouldComponentUpdate method, which didn’t check the new state change I’d added.

score:64

My scenario was a little different. And I think that many newbies like me would be stumped - so sharing here.

My state variable is an array of JSON objects being managed with useState as below:

const [toCompare, setToCompare] = useState([]);

However when update the toCompare with setToCompare as in the below function - the re-render won't fire. And moving it to a different component didn't work either. Only when some other event would fire re-render - did the updated list show up.

const addUniversityToCompare = async(chiptoadd) =>
  {
      var currentToCompare = toCompare;
      currentToCompare.push(chiptoadd);
      setToCompare(currentToCompare);
  }

This was the solution for me. Basically - assigning the array was copying the reference - and react wouldn't see that as a change - since the ref to the array isn't being changed - only content within it. So in the below code - just copied the array using slice - without any change - and assigned it back after mods. Works perfectly fine.

const addUniversityToCompare = async (chiptoadd) => {
    var currentToCompare = toCompare.slice();
    currentToCompare.push(chiptoadd);
    setToCompare(currentToCompare);
}

Hope it helps someone like me. Anybody, please let me know if you feel I am wrong - or there is some other approach.

Thanks in advance.

score:100

I'd like to add to this the enormously simple, but oh so easily made mistake of writing:

this.state.something = 'changed';

... and then not understanding why it's not rendering and Googling and coming on this page, only to realize that you should have written:

this.setState({something: 'changed'});

React only triggers a re-render if you use setState to update the state.


Related Query

More Query from same tag