score:3

Accepted answer

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();
};

score:0

My implementation below does not use async/await. If you need to wait until setState is complete, you're probably better off going with Tholle's answer. However, mine is a tad cleaner if you simply want to return an object with values irrespective of whether the state has been fully set.

myFunction = () => {
  let returnData;
  this.setState(state => {
    // do some stuff here
    returnData = { originalBar, newBar: state.foo };
    return {
      foo: "bar"
    };
  });

  return returnData;
}

otherFunction = () => {
  var originalValue = this.myFunction();
}

However, I would not recommend this, and instead I would try not to use a functional callback in this.setState.

Perhaps you could do something like this?

const originalBar = this.state.foo; // or whatever it might be
const newBar = "bar";
this.setState({ foo: newBar });
return { originalBar, newBar };

Quite a bit shorter, and quite a bit more elegant.

score:0

Looks like you want to acces the previous state and the current state. Rather than using setState to do something that is not intended for it, you can use life cycle methods in react which provide you with the previous state as well as previous props depending upon your usecase.

componentDidUpdate(prevProps, prevState, snapshot){
  ...
}

or

getSnapshotBeforeUpdate(prevProps, prevState){
...
}

Related Query

More Query from same tag