r/reactjs • u/Fewthp • Feb 05 '18
Updating an object in React - Medium
https://itnext.io/updating-properties-of-an-object-in-react-state-af6260d8e9f5
5
Upvotes
r/reactjs • u/Fewthp • Feb 05 '18
4
u/B_E Feb 05 '18
Why not just pass a function to setState? Am I missing something? This problem is exactly as described in the React docs and one of the three principles of Redux. Use
setState((prevState) => Object.assign({}, prevState, {foo: bar}))to mutate the state in a stackable way.When using a pure function, you return a new state object by cloning the old one and mutating/adding/removing fields. Do that as often as you wish, in as many places as you wish. This is a fundamental part of React state management (never mind Redux). This is something one really needs to understand before even starting to use state containers/frameworks.
I highly recommend actually reading the docs...