How to: persist a valtio state

Why valtio?

  • One global store
  • Multiple action creators
  • Many reducer functions
  • Thunks/sagas to handle async operations
  • You may also use reselect to create computed values
  • Working with immutable data may need additional care
  • Multiple state objects based on your app’s features
  • Actions are plain functions which directly modify the state. No reducers required. Since these can be async functions, you don’t necessarily need additional abstractions to handle async operations

Local persistence

import { proxy } from 'valtio';

const state = proxy({ todos: [] });
subscribe(state, () => {
localStorage.set('todosState', JSON.stringify(state));
});
const storedStateString = localStorage.getItem('todosState');
const initialState = storedStateString ? JSON.parse(storedStateString) : { todos: [] };
// states/todos.js
import { proxy } from 'valtio';
const storedStateString = localStorage.getItem('todosState');
const initialState = storedStateString ? JSON.parse(storedStateString) : { todos: [] };
const state = proxy(initialState);subscribe(state, () => {
localStorage.set('todosState', JSON.stringify(state));
});
export default state;

React Native & AsyncStorage

// states/todos.js
import AsyncStorage from '@react-native-async-storage/async-storage';
import { proxy } from 'valtio';

const state = proxy({ todos: [], hydrated: false });
subscribe(state, () => {
AsyncStorage.setItem('todosState', JSON.stringify(state));
});
export const hydrateState = async () => {
const storedStateString = await AsyncStorage.getItem('todosState');
if(storedStateString){
state.todos = JSON.parse(storedStateString).todos;
}
state.hydrated = true;
}
export default state;// App.tsx
import { useSnapshot } from 'valtio';
import React, { useEffect } from 'react';
import state, { hydrateState } from './states/todos';
const App = () => {
const { hydrated, todos } = useSnapshot(state);
useEffect(() => {
hydrateState();
}, []);
if(hydrated){
// Return your actual component which renders the app
}
// return a loading screen
}

Closing thoughts

--

--

You may check my website for my bio, at http://t.co/BlvwH2JyeT.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store