We will learn how to use store.subscribe() to efficiently persist some of the app’s state to localStorage and restore it after a refresh.

To save data in to localStroge,  we first create a localStorgejs file and two methods, one for get and one for set:

export const loadState =  () => {
// Important to use try catch for localStorage if browser doesn't support local storge
try{
const serializedState = localStorage.getItem('state');
if(serializedState === null){
// if there is no item stored, then use default ES6 param
return undefined;
}else{
return JSON.parse(serializedState)
}
}catch(err){
return undefined;
}
} export const saveState = (state) => {
try{
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
}catch(err){
console.error("Cannot save to storage");
}
}

The data we want to save into localStorage should be serializable. And should use try and catch to handle error.

Use loadState() to get presisted data and to create store:

const persistedState = loadState();
const store = createStore(todoApp, persistedState);

Subscribe to the store, everytime there is something changed, save the todos into localStorge:

store.subscribe( () => {
const {todos} = store.getState();
saveState({
todos
})
})

If already save some todos into the localStroge and refresh the app, then we find that we cannot save any todo anymore. this is because in the application we use 'nextTodoId':

let nextTodoId = 0;
export const addTodo = (text) => ({
type: 'ADD_TODO',
id: (nextTodoId++).toString(),
text,
});

Everytime page refresh it will start from zero again, then it cause the problem.

Install:

npm i --save node-uuid

node-uuid has a method call v4() to generate a random id:

// Generate a v4 (random) id
uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'

We can use it to replace the old implemention:

import {v4} from 'node-uuid';

export const addTodo = (text) => ({
type: 'ADD_TODO',
id: v4(),
text,
});

One thing to be improved is everytime we update the stroe, saveState() function will be invoked. We want to add throttle to it:

Install:

npm i --save lodash
import throttle from 'lodash/throttle';

const persistedState = loadState();
const store = createStore(todoApp, persistedState); store.subscribe( throttle(() => {
const {todos} = store.getState();
saveState({
todos
})
}, 1000));

------------------------------

If look at the tests for createStore(), the second args can accpet 'undefined', [], {}, fn but NOT null. So it is important to return 'undefined' let reducer accept the ES6 default param.

See Link: https://github.com/reactjs/redux/blob/master/test/createStore.spec.js#L546

[Redux] Persisting the State to the Local Storage的更多相关文章

  1. [MST] Store Store in Local Storage

    For an optimal user and developer experience, storing state in local storage is often a must. In thi ...

  2. Ionic2学习笔记(8):Local Storage& SQLite

    作者:Grey 原文地址: http://www.cnblogs.com/greyzeng/p/5557947.html              Ionic2可以有两种方式来存储数据,Local S ...

  3. Web持久化存储Web SQL、Local Storage、Cookies(常用)

    在浏览器客户端记录一些信息,有三种常用的Web数据持久化存储的方式,分别是Web SQL.Local Storage.Cookies. Web SQL 作为html5本地数据库,可通过一套API来操纵 ...

  4. cookie ,session Storage, local storage

    先来定义: cookie:是网站为了标识用户身份存储在本地终端的数据,其数据始终在APP请求中存在,会在服务器和浏览器中来回传递 数据大小不超过4k, 可以设置有效期,过了有效期自动删除 sessio ...

  5. Session,Cookie 和local storage的区别

    以前从没有听说过local storage, 在网上查了一些资料,得到如下结论 从存储位置看,分为服务器端存储和客户端存储两种 服务器端: session 浏览器端: cookie, localSto ...

  6. 关于local storage及session storage 应用问题

    H5- storage 可以在不同页面内进行数据传递数据信息,保证了数据传输不许后台交互即可在前端部分自我实现,以下为local storage 应用个人简析: * localStorage * se ...

  7. 关于local storage 和 session storage以及cookie 区别简析

    session storage 和local storage 都是存储在客户端的浏览器内: 一:关于COOKIE 的缺陷 * Cookie的问题 * 数据存储都是以明文(未加密)方式进行存储 * 安全 ...

  8. local storage 简单应用‘’记住密码’

    前些时候一直用cookie等来进行登录页面记住面膜操作,但是由于其存储容量小等缘故,所以后来转向local storage,原理为:当用户勾选记住密码时,local storage 存储用户名密码同时 ...

  9. web页面缓存技术之Local Storage

    业务:检测页面文本框的值是否有改变,有的话存入缓存,并存储到数据库,这样用户异常操作后再用浏览器打开网页,就可避免重新填写数据 数据库表:Test,包含字段:PageName,PageValue BL ...

随机推荐

  1. 探讨 yum 与 rpm 的安装包数量

    安装包数量不相等 [root@localhost ~]# rpm -qa | wc –l #列出所有被安装的rpm package 422 [root@localhost ~]# yum list i ...

  2. shell 1变量注意点

    定义变量时,变量名不加美元符号($),如: variableName="value" 注意,变量名和等号之间不能有空格,这可能和你熟悉的所有编程语言都不一样. 删除变量 使用 un ...

  3. python中跟字符串相关的一些操作

    公司让用python自动生成代码,以前没看过python.所以匆匆的看了两天python就连猜带蒙就上马开干了..因此好多操作可能看的时候看懂了,用的时候知道有这么个东西,具体用法就忘记了..用到了就 ...

  4. Docker Machine

    Docker Machine http://dockone.io/article/1485?utm_source=tuicool&utm_medium=referral 本地安装与使用 Doc ...

  5. Android Audio 分析

    一.架构 二.MediaServer初始化 所有的media服务都在进程mediaserver里.其代码在framework/base/media/mediaserver/main_mediaserv ...

  6. 完全卸载mysql 停止服务、卸载相关程序、删除注册表

    本节主要介绍了完全卸载mysql的具体步骤包括停止服务.卸载相关程序.删除注册表等等   1. 停止服务MySQL 2. 卸载mysql相关的程序 3. 删除注册表(运行->regedit),m ...

  7. Codeforces Round #207 (Div. 2)

    A:超级大水题: 代码: #include<cstdio> #define maxn 105 using namespace std; int n,a[maxn],x,y,ans; int ...

  8. win7 热点设置命令

    netsh wlan set hostednetwork mode=allownetsh wlan set hostednetwork ssid=XXXX key=XXXnetsh wlan star ...

  9. gridview数据导出到word和excel以及excel的导入

    using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI ...

  10. 用F340 GPIO做I2C

    在和Qinheng开发小尺寸点灯治具中,F340和FPGA采用I2C通信,其中F340作为I2C的主机,I2C端口用自己的GPIO编写,总结遇到的问题及注意事项: 1.  F340端口及上拉电阻设置: ...