Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async return value from setState [duplicate]

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.

like image 877
cubefox Avatar asked Oct 16 '22 05:10

cubefox


1 Answers

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();
};
like image 105
Tholle Avatar answered Oct 29 '22 22:10

Tholle