persist
Overview
Section titled “Overview”The persist function allows you to persist the state of a ref in the browser’s localStorage by associating it with a unique key. This enables you to store and retrieve the state of the ref across page reloads or even when the browser is closed and reopened.
Persisting a Ref
Section titled “Persisting a Ref”To persist the state of a ref, call the persist function, passing the ref you want to persist and a unique key as arguments. The key is used to identify the stored data in localStorage.
import { ref, persist } from 'regor'
// Create a refconst myRef = ref(5)
// Persist the ref with a unique keypersist(myRef, 'myPersistedRef')Retrieving a Persisted Ref
Section titled “Retrieving a Persisted Ref”You can retrieve a persisted ref by calling the persist function again with the same key. If the data for that key exists in localStorage, the ref’s state will be restored from the stored data.
// Retrieve a previously persisted refconst myPersistedRef = persist(ref(0), 'myPersistedRef')
console.log(myPersistedRef.value) // Output: The value stored in localStorageParameters
Section titled “Parameters”-
anyRef(required): The ref that you want to persist inlocalStorage. -
key(required): A string key that uniquely identifies the persisted data inlocalStorage.
Return Value
Section titled “Return Value”The persist function returns the same ref that was passed as anyRef. This allows you to use the ref as usual in your application.
-
The
persistfunction is particularly useful for preserving the state of application data, user preferences, or settings across different browser sessions. -
It leverages the
localStorageAPI to store and retrieve data, making it accessible even after the browser is closed and reopened. -
If the
localStoragedata for the specifiedkeydoes not exist (e.g., during the first use or after clearing browser data), thepersistfunction will store the initial state of the ref inlocalStorage. -
To update the persisted data, simply modify the ref’s value, and the changes will be automatically stored in
localStorageand synchronized across different browser sessions.