example of persisting state using @xstate/store #5208
Answered
by
davidkpiano
jericopulvera
asked this question in
Q&A
-
|
Can we add an example of this in the docs. |
Beta Was this translation helpful? Give feedback.
Answered by
davidkpiano
Feb 18, 2025
Replies: 1 comment
-
|
Yes, good idea. Here's an example: // Example of a counter store with localStorage persistence
const savedSnapshot = localStorage.getItem('store');
const initialSnapshot = savedSnapshot ? JSON.parse(savedSnapshot) : {
context: {
count: 0,
lastUpdated: Date.now(),
// ... any other state properties
}
};
const counterStore = createStore({
context: initialSnapshot.context,
on: {
increment: (context, event: { amount: number }) => ({
...context,
count: context.count + event.amount,
lastUpdated: Date.now()
}),
decrement: (context, event: { amount: number }) => ({
...context,
count: context.count - event.amount,
lastUpdated: Date.now()
})
}
});
// Handle persistence via subscription - persist entire snapshot
counterStore.subscribe((snapshot) => {
localStorage.setItem('store', JSON.stringify(snapshot));
});
// Usage
counterStore.send({ type: 'increment', amount: 5 });
counterStore.send({ type: 'decrement', amount: 2 }); |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
jericopulvera
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, good idea. Here's an example: