Skip to content

Instantly share code, notes, and snippets.

@garethpbk
Created November 20, 2018 17:36
Show Gist options
  • Save garethpbk/1dd9290026c5e1a6f31ec7163fdc86e7 to your computer and use it in GitHub Desktop.
Save garethpbk/1dd9290026c5e1a6f31ec7163fdc86e7 to your computer and use it in GitHub Desktop.
apollo-link-rest nested state management example
state = {
name: '',
username: '',
email: '',
address: {
street: '',
suite: '',
city: '',
zipcode: '',
geo: {
lat: '',
lng: '',
},
},
phone: '',
website: '',
company: {
name: '',
catchPhrase: '',
bs: '',
},
};
handleChange = (e, nested = null, doubleNested = null) => {
const {
target: { name, value },
} = e;
if (doubleNested) {
const updateObj = { ...this.state[nested][doubleNested] };
updateObj[name] = value;
this.setState(prevState => ({
[nested]: {
...prevState[nested],
[doubleNested]: updateObj,
},
}));
} else if (nested && !doubleNested) {
const updateObj = { ...this.state[nested] };
updateObj[name] = value;
this.setState({
[nested]: updateObj,
});
} else {
this.setState({
[name]: value,
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment