Reputation: 447
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
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, usecomponentDidUpdate
or a setState callback (setState(updater, callback)
), either of which are guaranteed to fire after the update has been applied.
(Emphasis mine.)
Upvotes: 1
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