Created
December 2, 2021 17:31
-
-
Save scottopolis/4753483341510d3dc57355b2676025c1 to your computer and use it in GitHub Desktop.
React set state for object property (one-liner)
This file contains hidden or 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
// to update a property in an object, for example a title | |
setMyState({ | |
...currentState, | |
title: newTitle, | |
}); | |
/* Explanation below... | |
// we have an object set as state | |
const post = { id: 2, title: 'My Post', content: 'This is my post.' }; | |
setPost(post); | |
// we want to update only one property, the title, but we can't edit state directly, so we create a new object then save it to state | |
let newPost = { ...post }; | |
newPost.title = "Update my title"; | |
setPost(newPost); | |
// instead, you can do | |
let newTitle = "Update my title"; | |
setPost({ | |
...post, | |
title: newTitle, | |
}); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment