Last active
September 18, 2017 09:14
-
-
Save amite/003474614b1d341f3705569e6aff6015 to your computer and use it in GitHub Desktop.
Immutable Updates to nested data with setState in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Functional setState (Recommended) | |
this.setState(prevState => { | |
const newState = { | |
...prevState.data, | |
transactions: [...data, prevState.data.transactions] | |
} | |
return { data: newState } | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Just plain setState (not recommended) | |
this.setState({ | |
data: { | |
...this.state.data, | |
transactions: [...this.state.data.transactions, ...data] | |
} | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// what your state might look like while doing deep updates | |
// Keep state shallow! Don't nest beyond two levels | |
state = { | |
data: { | |
transactions: [] | |
}, | |
form: { | |
note: '', | |
deposit: App.DEFAULT_DEPOSIT_AMOUNT, | |
spend: App.DEFAULT_EXPENSE_AMOUNT, | |
date: moment(), | |
isValid: false | |
}, | |
ui: { | |
isActive: false, | |
message: '', | |
loading: true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment