Skip to content

Instantly share code, notes, and snippets.

@paveli
Last active May 23, 2019 10:34
Show Gist options
  • Save paveli/a37f109452590ff65b1c1f5ee91c3f1b to your computer and use it in GitHub Desktop.
Save paveli/a37f109452590ff65b1c1f5ee91c3f1b to your computer and use it in GitHub Desktop.
question about how setState works

Hi, I have a question about how setState works in React connected to how async JavaScript works in general :)

Lets say in one class-based component I have state with nestedObject

state = {
	nestedObject: {
		propertyOne: false,
		propertyTwo: false,
		propertyAnother: false
	}
};

And two validator functions that in the end change nestedObject in the state

validateOne = () => {
    //... some logic before
	this.setState(state => {
		return {
			nestedObject: {
				...state.nestedObject,
				propertyOne: someCheck() // someCheck() returns true or false
			}
		};
	});
};

validateTwo = () => {
    //... some logic before
	this.setState(state => {
		return {
			nestedObject: {
				...state.nestedObject,
				propertyTwo: someCheck() // someCheck() returns true or false
			}
		};
	});
};

As in validateOne and in validateTwo I fulfill nestesObject with its properties using ...state.nestedObject. Can I be sure that setState in validateTwo will receive updated state (after state update by setState in validateOne)? So can I safely run it like that:

this.validateOne();
this.validateTwo();

Or should I chain it with Promise? To be sure that setState in validateTwo method will not take old state as parameter?

validateOnePromise = () => {
	return new Promise(resolve => {
        //... some logic before
		this.setState(state => {
			return {
				nestedObject: {
					...state.nestedObject,
					propertyOne: someCheck() // someCheck() returns true or false
				}
			};
		}, resolve());
	});
};

And run the code like that? this.validateOnePromise().then(this.validateTwo());

I understand that setState is kinda "async" by nature. And that it has callback function that may be used for chaining. But as I know that validateOne will be executed before validateTwo? Can I be suree that state passed to setState in validateTwo is new updated state?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment