hisusu32
hisusu32

Reputation: 447

React Typescript: can't set State

I have an array that contains a string. I'm trying to take that string and join it with another string. When I console.log('Dates: ' + mergedActions) I get back both strings together. However when I console.log('Dates: ' + this.state.MergedAllActions) it's empty. I tried adding a timeout to the console log but still nothing.

Any idea why mergedActions even though it contains information doesn't get set in MergedAllActions?

let currentAction = 'Form has been submitted';
let mergedActions = this.state.Product[0].AllActions + ',' + currentAction;
this.setState({ MergedAllActions: mergedActions });
console.log('Dates: ' + mergedActions);  
console.log('Dates: ' + this.state.MergedAllActions);

Console below:

Dates: first Step,First Approver accepted
Dates:

 

Upvotes: 0

Views: 521

Answers (2)

AKX
AKX

Reputation: 168863

setState is asynchronous, as the documentation explains:

setState() enqueues changes to the component state [...]
Think of setState() as a request rather than an immediate command to update the component. [...]
setState() does not always immediately update the component. [...] This makes reading this.state right after calling setState() a potential pitfall.
Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.

(Emphasis mine.)

Upvotes: 1

nip
nip

Reputation: 1697

setState is asynchronous, but it supports a callback as the 2nd argument. Change to

this.setState({ MergedAllActions: mergedActions }, console.log(this.state.MergedAllActions));

Upvotes: 1

Related Questions