-
Notifications
You must be signed in to change notification settings - Fork 330
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Discussion: Cloning before setting state #494
Comments
Mutating state directly is definitely improper practice. Not just here, but even in React itself it's called out as something not do do. You could very well get the same issue if you tried to do that on a normal React component's state. From the React docs:
The proper way to do it is the way you described later, something like: this.setState({toggled: !this.state.toggled}); And not just for the reason of avoiding directly mutating state either. In your first example if state had more properties than just But lastly: I'm also fairly sure cloning would not solve this. You mutated the state before |
@BryanGrezeszak can we check if the last and next state are the same? Then we can show a warning or something like that. |
@dodekeract - If you mean for part of Reflux detect whether the state has been mutated directly: unfortunately no. That's actually the whole reason for I mean, you could clone/check repeatedly, but that would dodgy, and at best only be useful enough for warnings and would probably add about as much overhead as the rest of the running library's features combined (which is not a good feature vs. cost ratio at all). And, on top of that, even if we did that in Reflux...React doesn't. So it makes more sense to just piggyback off React and say "you can't mutate it directly in React, so don't mutate it directly here." Honestly, if there were an efficient and practical way to detect direct state mutation of simple objects then both React and Reflux wouldn't use something like |
I've had this problem multiple times before, I don't know if I should be more careful or to actually fix it in the core.
The problem is, by getting the value from a store, like:
the problem is by having the whole object into currentState, and modifying it, also modifies in the current StoreState via object reference.
so when I then try to see if a Component that listens to a store should update.
nextState and this.state.toggled is actually the same state. I know this can be avoided by only setting in the Store:
But I'm thinking that more people would have this issue (especially when dealing with multi-level objects), wouldn't it be better for cloning the state before setting it?
Like changing in
defineReact.js
whensS(updateObj);
tosS(clone(updateObj));
and
this.setState(updateObj);
tothis.setState(clone(updateObj));
This will definitely prevent all reference issues and it will be the same as
Reflux.getGlobalState
What do you guys think?
The text was updated successfully, but these errors were encountered: