Skip to content

Instantly share code, notes, and snippets.

@amite
Last active September 18, 2017 09:14
Show Gist options
  • Save amite/003474614b1d341f3705569e6aff6015 to your computer and use it in GitHub Desktop.
Save amite/003474614b1d341f3705569e6aff6015 to your computer and use it in GitHub Desktop.
Immutable Updates to nested data with setState in React
// Functional setState (Recommended)
this.setState(prevState => {
const newState = {
...prevState.data,
transactions: [...data, prevState.data.transactions]
}
return { data: newState }
})
// Just plain setState (not recommended)
this.setState({
data: {
...this.state.data,
transactions: [...this.state.data.transactions, ...data]
}
})
// 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