I want to accomplish the following:
myFunction = () => {
this.setState(
state => {
const originalBar = state.bar;
return {
foo: "bar"
};
},
() => ({ originalBar, newBar: state.foo }) //return this object
);
};
otherFunction = () => {
var originalValue = myFunction(); //access returned object (in child component)
};
setState doesn't return anything and the only way I could figure how to do this was calling a callback to my function
in the setState callback, however, I'd prefer doing this with async await if that's possible.
You can return a new Promise
from myFunction
that is resolved in the callback to setState
.
Then you can use async
/await
in your otherFunction
.
myFunction = () => {
return new Promise(resolve => {
let originalFoo;
this.setState(
state => {
originalFoo = state.foo;
return {
foo: "bar"
};
},
() => resolve({ originalFoo, newFoo: this.state.foo })
);
});
};
otherFunction = async () => {
var originalValue = await myFunction();
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With