Created
November 20, 2018 17:36
-
-
Save garethpbk/1dd9290026c5e1a6f31ec7163fdc86e7 to your computer and use it in GitHub Desktop.
apollo-link-rest nested state management example
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
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