Skip to content

Instantly share code, notes, and snippets.

@scottopolis
Created December 2, 2021 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottopolis/4753483341510d3dc57355b2676025c1 to your computer and use it in GitHub Desktop.
Save scottopolis/4753483341510d3dc57355b2676025c1 to your computer and use it in GitHub Desktop.
React set state for object property (one-liner)
// 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