0

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:

 

2 Answers 2

1

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

this.setState({ MergedAllActions: mergedActions }, console.log(this.state.MergedAllActions));
Sign up to request clarification or add additional context in comments.

Comments

1

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.)

2 Comments

Hi thanks for the reply, I'm still new to react. So I'm doing this in a submit function. On submit I'm doing this calculations then pushing the new set state to my array any ideas?
As the doc fragment above explains, the change to your state is not immediately available after you call setState(), since setState() is asynchronous. It will be reflected in state when the component is re-rendered the next time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.