summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/vue_shared/components/local_storage_sync.vue
diff options
context:
space:
mode:
Diffstat (limited to 'app/assets/javascripts/vue_shared/components/local_storage_sync.vue')
-rw-r--r--app/assets/javascripts/vue_shared/components/local_storage_sync.vue33
1 files changed, 27 insertions, 6 deletions
diff --git a/app/assets/javascripts/vue_shared/components/local_storage_sync.vue b/app/assets/javascripts/vue_shared/components/local_storage_sync.vue
index 33e77b6510c..4ece87310c7 100644
--- a/app/assets/javascripts/vue_shared/components/local_storage_sync.vue
+++ b/app/assets/javascripts/vue_shared/components/local_storage_sync.vue
@@ -1,6 +1,18 @@
<script>
-import { isEqual } from 'lodash';
+import { isEqual, isString } from 'lodash';
+/**
+ * This component will save and restore a value to and from localStorage.
+ * The value will be saved only when the value changes; the initial value won't be saved.
+ *
+ * By default, the value will be saved using JSON.stringify(), and retrieved back using JSON.parse().
+ *
+ * If you would like to save the raw string instead, you may set the 'asString' prop to true, though be aware that this is a
+ * legacy prop to maintain backwards compatibility.
+ *
+ * For new components saving data for the first time, it's recommended to not use 'asString' even if you're saving a string; it will still be
+ * saved and restored properly using JSON.stringify()/JSON.parse().
+ */
export default {
props: {
storageKey: {
@@ -12,7 +24,7 @@ export default {
required: false,
default: '',
},
- asJson: {
+ asString: {
type: Boolean,
required: false,
default: false,
@@ -30,6 +42,8 @@ export default {
},
watch: {
value(newVal) {
+ if (!this.persist) return;
+
this.saveValue(this.serialize(newVal));
},
clear(newVal) {
@@ -67,15 +81,22 @@ export default {
}
},
saveValue(val) {
- if (!this.persist) return;
-
localStorage.setItem(this.storageKey, val);
},
serialize(val) {
- return this.asJson ? JSON.stringify(val) : val;
+ if (!isString(val) && this.asString) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[gitlab] LocalStorageSync is saving`,
+ val,
+ `to the key "${this.storageKey}", but it is not a string and the 'asString' prop is true. This will save and restore the stringified value rather than the original value. If this is not intended, please remove or set the 'asString' prop to false.`,
+ );
+ }
+
+ return this.asString ? val : JSON.stringify(val);
},
deserialize(val) {
- return this.asJson ? JSON.parse(val) : val;
+ return this.asString ? val : JSON.parse(val);
},
},
render() {