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. 在CAD中怎么画圆形视口的详细说明

    方法如下:在布局下画一个合适的圆,然后:命令: _-vports指定视口的角点或[开(ON)/关(OFF)/布满(F)/消隐出图(H)/锁定(L)/对象(O)/多边形(P)/恢复(R)/2/3/4]& ...

  2. Python正则表达式2

  3. "git add -A" is equivalent to "git add .; git add -u".

    git add -A stages All git add . stages new and modified, without deleted git add -u stages modified ...

  4. NSURLSession -- 备忘

    NSURLSession NSURLSession是iOS7出的API,在它之前常用的原生网络库是NSURLConnection,但是因为Connection的使用起来不是很方便 所以我们一直倾向于A ...

  5. Js 简单分页(一)

    网上有很多分页的插件 但是没有自己想要的 上代码吧,只有分页部分代码,css 省略了 html <div class="bar2 fr" id="pagecontr ...

  6. 小记,取GB2312汉字的首字母【转】

    /// <summary> /// PY 的摘要说明. /// </summary> public class PY { // Fields private string m_ ...

  7. 计算字符串的最长回文子串 :Manacher算法介绍

    转自: http://www.open-open.com/lib/view/open1419150233417.html Manacher算法 在介绍算法之前,首先介绍一下什么是回文串,所谓回文串,简 ...

  8. Keil编译后的各文件介绍

    编译生成的文件: .plg:编译器编译结果 .hex和.bin:可执行文件 .map和.lst:链接文件 .obj:目标文件 .crf..lnp..d和.axf:调试文件 .opt:保存工程配置信息 ...

  9. .classpath 和.project文件含义

    .classpath文件是在建立eclipse工程时创建的描述工程配置情况的文件,包括:  * 源码路径  * 编译结果的输出路径  * 所使用的外部库的路径 -----------------下面是 ...

  10. xlslib安装, aclocal-1.13: command not found, 安装升级autoconf-2.65.tar.gz, automake-1.13.tar.gz两个文件

    问题1: $ make CDPATH="${ZSH_VERSION+.}:" && cd . && aclocal-1.13 -I m4 /bin/ ...