Add ability to persist state values in local storage

This commit is contained in:
Andrew Kingston 2021-08-26 17:52:04 +01:00
parent 0f6a7946b5
commit 3eea601910
3 changed files with 41 additions and 10 deletions

View File

@ -1,5 +1,5 @@
<script>
import { Select, Label, Combobox } from "@budibase/bbui"
import { Select, Label, Combobox, Checkbox } from "@budibase/bbui"
import { onMount } from "svelte"
import DrawerBindableInput from "components/common/bindings/DrawerBindableInput.svelte"
import { getAllStateVariables } from "builderStore/dataBinding"
@ -42,6 +42,8 @@
value={parameters.value}
on:change={e => (parameters.value = e.detail)}
/>
<div />
<Checkbox bind:value={parameters.persist} text="Persist this value" />
{/if}
</div>

View File

@ -1,21 +1,50 @@
import { writable } from "svelte/store"
import { writable, get, derived } from "svelte/store"
import { localStorageStore } from "../../../builder/src/builderStore/store/localStorage"
import { appStore } from "./app"
const createStateStore = () => {
const store = writable({})
const localStorageKey = `${get(appStore).appId}.state`
const persistentStore = localStorageStore(localStorageKey, {})
const setValue = (key, value) => {
store.update(state => {
// Initialise the temp store to mirror the persistent store
const tempStore = writable(get(persistentStore))
// Sets a value to state, optionally persistent
const setValue = (key, value, persist = false) => {
const storeToSave = persist ? persistentStore : tempStore
const storeToClear = persist ? tempStore : persistentStore
storeToSave.update(state => {
state[key] = value
return state
})
}
const deleteValue = key => {
store.update(state => {
storeToClear.update(state => {
delete state[key]
return state
})
}
// Delete a certain key from both stores
const deleteValue = key => {
const stores = [tempStore, persistentStore]
stores.forEach(store => {
store.update(state => {
delete state[key]
return state
})
})
}
// Derive the combination of both persisted and non persisted stores
const store = derived(
[tempStore, persistentStore],
([$tempStore, $persistentStore]) => {
return {
...$tempStore,
...$persistentStore,
}
}
)
return {
subscribe: store.subscribe,
actions: { setValue, deleteValue },

View File

@ -124,9 +124,9 @@ const closeScreenModalHandler = () => {
}
const updateStateHandler = action => {
const { type, key, value } = action.parameters
const { type, key, value, persist } = action.parameters
if (type === "set") {
stateStore.actions.setValue(key, value)
stateStore.actions.setValue(key, value, persist)
} else if (type === "delete") {
stateStore.actions.deleteValue(key)
}