Cloning JS Objects & Form Handling With Vuex
May 01, 2020
Cloning JS Objects
Today I was reminded of a 101 rule about JavaScript objects: if you try to copy an object by creating a new variable and setting it equal to the original object, it only creates a reference to the original object, rather than actually copying it. This article Deep Cloning Objects In JavaScript (And How It Works) explains it way better than I’ll aim to do here. But long story short, if you need to create an actual copy of an object, const objCopy = obj
isn’t going to cut it!
The article above recommends using the lodash library’s cloneDeep
method to ensure you get an actual copy, no matter what’s in your original object. I opted to do this in my project, and only imported the single function: import { cloneDeep } from 'lodash';
.
Another option mentioned in this article is to use Object.assign()
, and in most cases (in fact, in the use case I was working with) this will work, even when there are nested objects. It won’t work though if there are functions within any part of the original object, so this way of cloning an object needs to be used with care.
Form Handling With Cancel/Save Buttons & Vuex Store
All of the above came in handy trying to figure out how to work with edit forms in Vue when the questions come from a Vuex store. Rather than setting v-model
to the object itself directly from state, I created a local-to-the-component copy of the state object first, and set v-model
on the copy. This way the user can make edits, hit a cancel button, and everything reverts back to the original state. To save the user’s changes, I send the edited, copied object to the API update route.
These are the resources that helped me figure out how to do this:
- StackOverflow: Save or Cancel edits in vue/vuex
- StackOverflow: Editing a form with save and cancel options (also demonstrates another way to do it using refs)
- YouTube: VueX Strict Mode - Write better forms while keeping all VueX State changes inside mutation
- YouTube Playlist: Building a VueJS screencasting app from scratch
Also I didn’t do this, but it might be interesting to store unsaved form data in local storage so that it’s still there if the user accidentally leaves the page…this article walks through a way to do it.