乐闻世界logo
搜索文章和话题

How to save Mobx state in sessionStorage

1个答案

1

To save Mobx state in sessionStorage, we can leverage Mobx's reactive mechanism and the browser's sessionStorage API. This allows us to utilize the convenience of Mobx for state management while automatically clearing the data when the user closes the browser tab, as sessionStorage's storage duration is limited to the page session.

Steps and Example Code:

Step 1: Create a Mobx Store

First, we need a Mobx store. Here's a simple example:

javascript
import { makeAutoObservable } from "mobx"; class UserStore { userInfo = { name: "", age: 0 }; constructor() { makeAutoObservable(this); } setUserInfo(userInfo) { this.userInfo = userInfo; } } const userStore = new UserStore(); export default userStore;

Step 2: Listen for Store Changes and Update sessionStorage

We can use the autorun function from the mobx library to automatically listen for any changes that might affect the state and update sessionStorage. This way, whenever the data in the store changes, we synchronize the update to sessionStorage.

This code monitors the userInfo object within userStore. Whenever userInfo changes, it automatically serializes the updated userInfo into a JSON string and stores it in sessionStorage.

Step 3: Restore State from sessionStorage (if necessary)

When the user reopens the page, we can check sessionStorage for any previously saved state during application load and initialize the store accordingly.

This code attempts to retrieve userInfo from sessionStorage. If it exists, it parses the JSON string and uses the parsed data to set the store's state.

Summary:

By doing this, we can ensure that the Mobx state remains consistent during the page session and is automatically cleared when the user closes the browser tab. This approach is both simple and effective, allowing for tighter integration between state management and persistence.

2024年8月16日 00:14 回复

你的答案