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. ubuntu chm文档阅读

    四种方法在Ubuntu下查看CHM文件 来源:http://os.51cto.com/art/201108/287748.htm Ubuntu是一个以桌面应用为主的Linux操作系统,刚开始使用Ubu ...

  2. Python学习 - 简单抓取页面

    最近想做一个小web应用,就是把豆瓣读书和亚马逊等写有书评的网站上关于某本书的打分记录下来,这样自己买书的时候当作参考. 这篇日志这是以豆瓣网为例,只讨论简单的功能. 向服务器发送查询请求 这很好处理 ...

  3. dictionary ----- python

    Learn of dictionary,simple example of dictionary in  “Simple Python tutorial"------------------ ...

  4. linux下date命令实现时间戳与日期的转换

    1.查看指定时间的时间戳    查看当前时间  #date +%s    查看指定时间  #date -d 2008-01-01 +%s   1199116800  #date -d 20080101 ...

  5. Ipv6_Only-b

    网上好多关于ipv6的资料,说半天ipv6是什么,怎么建立测试环境,,,可是没有看到具体的操作和解决的方案,这里,为大家提供一种方案,希望给大家带来帮助吧. 总的来说有三个方面需要进行检查和修改: 1 ...

  6. PyCharm使用技巧记录(一)如何查看变量

    [为了方便自己以后查阅,记录下使用PyCharm时的一些小技巧] 正在学习Python,在调试Python程序时,遇到了一个非常大的问题:如何能够方便地查看变量的取值呢? 由于使用matlab多年,深 ...

  7. BZOJ 4052 Magical GCD

    Description 给出一个长度在\(100000\)以内的正整数序列,大小不超过\(10^{12}\).求一个连续子序列,使得在所有的连续子序列中,它们的GCD值乘以它们的长度最大. Input ...

  8. windows下端口被占用的解决方法

    1:打开CMD输入:netstat -ano | findstr "80" 找到PID: 2:查看应用名称:tasklist | findstr "2544" ...

  9. A simple Gaussian elimination problem.

    hdu4975:http://acm.hdu.edu.cn/showproblem.php?pid=4975 题意:给你一个n*m的矩阵,矩阵中的元素都是0--9,现在给你这个矩阵的每一行和每一列的和 ...

  10. 安装drupal练习网站遇到的问题

    1 Skip #conjunction key in __clone() method of core/includes/database/query.inc 解决方案:https://www.dru ...