Best way to initialize state using asynchronous data #1052
Answered
by
overthemike
buiducnhat
asked this question in
Q&A
Replies: 2 comments 4 replies
-
|
Two options:
Sorry for the rough answer. Hope someone else can help! |
Beta Was this translation helpful? Give feedback.
1 reply
-
// state.js
import { proxy, subscribe } from 'valtio'
const emptySymbol = Symbol('Empty Value')
// First create a proxy with default values
export const state = proxy({
isLoaded: false, // optional
foo: emptySymbol
})
// Then load the stored values asynchronously
chrome.storage.local.get(['foo'], (result) => {
if (result.foo) {
const storedState = JSON.parse(result.foo)
// Update the proxy with stored values
Object.assign(state, storedState)
}
// state is loaded, so we can tell our application to use the values
state.isLoaded = true
})
// Set up subscription to persist changes
subscribe(state, () => {
chrome.storage.local.set({ foo: JSON.stringify(state) })
})// component.js
import { useSnapshot } from 'valtio'
import { state } from './state.js'
const App = () => {
const snap = useSnapshot(state)
if (!snap.isLoaded) {
return <p>Loading</p>
}
return (
<p>{state.foo}</p>
)
} |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
buiducnhat
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi everyone, I am new to valtio. And currently I want to apply it to my chrome extension.
Then I want to persist some data into extension storage, and of course I reference this guide https://github.com/pmndrs/valtio/blob/main/docs/how-tos/how-to-persist-states.mdx.
But following the guide,
localStorage.getItem()is a synchronous function, it's easy to implement, not likechrome.storage.local.get(), it return a promise.So I want to know how you guys will handle this case, thank you so much!
Beta Was this translation helpful? Give feedback.
All reactions