Valtio with persisted state #319
Replies: 3 comments 16 replies
-
Nicely done. const thing1 = proxy(INITIAL_STATE)
const add = () => { thing1.number += 1 }
export default thing1
export const thing1Actions = { add } |
Beta Was this translation helpful? Give feedback.
-
Thanks for the call out and trying out the lib. Way appreciate it!
That was a big one for me too, so I included that in the lib. :) I do have to add error handling, like when a file read fails it should log or something. redux-persist was also silent about errors, so I didn't prioritize this in v1. |
Beta Was this translation helpful? Give feedback.
-
For this image below, I see default export is The one reason I could see on wrapping initialState in proxy in that file, is if you want to make your actions work on that. So you don't have to re-import the persisted state. So the options I'm thinking of up there are this: Option 1 - export initial state and re-import persisted state
Option 2 - export proxied initial state, and connect actions to this proxy. no re-import of persisted stateI'm not sure if this actually works. But the idea here is to not re-import persisted state. Changes on this proxy will make the persisted proxy persist it.
and persisted:
|
Beta Was this translation helpful? Give feedback.
-
OK, I put about 20 hours into playing with and understanding Valtio over the last few days. Here's a little story and then a codesandbox with what I've come up with. Hopefully it helps others. Or @dai-shi can tell me I'm doing it wrong. 😀
We have a React Native app, token.art NFT viewer, that makes extensive use of "computed" state and persistence. Our current state package isn't being maintained and has some bugs. It is time to make the switch.
Here are the requirements.
<App>
is rendered.This codesandbox shows what I came up with.
The key insight came when reading the wiki. Specifically, How to Organize Actions. It gave me the inspiration to separate the exports. State is a
default export
and actions are grouped together in a singlenamed export
.This allowed the passing of only the state object to valtio-persist...
...and re-importing the persisted state proxy back into the "state" file for use in actions.
See (
import { state } from "./";
in thing.ts above).Then a nested folder structure with a well placed index file that re-exports all the named exports...
... leads to persisted and reactive state that is easy to access from the top level "store" import.
And last but not least... types are correctly inferred and used for auto-complete and visible on hover.
Now adding a new piece of persisted state is as simple as creating a new file in the state folder, adding the default import to persist, and reexporting the actions at the store level.
🎉
Here's the codesandbox again. Playing with it will help.
I'm very curious to hear anyone's opinions.
For now this is the approach I'm going to use in our app. 👍
Beta Was this translation helpful? Give feedback.
All reactions