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. windows下配置wnmp

    最近尝试windows下配置nginx+php+mysql,在这里总结一下. 1.下载windows版本的nginx,官网​下载地址:http://nginx.org/en/download.htm, ...

  2. Android开源项目(转载)

    第一部分 界面 ImageView.ProgressBar及其他如Dialog.Toast.EditText.TableView.Activity Animation等等. 一.ListView an ...

  3. python使用pyapns进行ios推送消息

    Pyapns 提供了通用的Apple Push Notification Service (APNS).该解决方案使用了开源的Twisted server,支持原生的Python和Ruby API. ...

  4. [译]36 Days of Web Testing(四)

    Day 19: UX  用户体验 Why ? 最近UX变得越来越火,用户提现往往会直接联想到易用性和设计. 在我看来,UX不仅仅是这两点.UX, User Experience ,对我而言,不单单是产 ...

  5. jquery学会的

    1.$("#id")    $("xxxxx") (input, body) $(".class") 2. $("#id  xxx ...

  6. jQuery遍历对象、数组、集合实例

    1.jquery 遍历对象 复制代码代码如下:   <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" ...

  7. Codeforces Round #204 (Div. 2): B

    很简单的一个题: 只需要将他们排一下序,然后判断一下就可以了! 代码: #include<cstdio> #include<algorithm> #define maxn 10 ...

  8. JSch - Java实现的SFTP(文件上传详解篇)(转)

    JSch是Java Secure Channel的缩写.JSch是一个SSH2的纯Java实现.它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到 ...

  9. 监听APP升级广播处理

    当旧版本的用户升级新版本的时候需要重新设定一些值处理,这时候需要监听升级版本的广播 <receiver android:name=".OnUpgradeReceiver"&g ...

  10. asp.net中水印的实现代码

    水印是为了防止别盗用我们的图片. 两种方式实现水印效果 1)可以在用户上传时添加水印. a)   好处:与2种方法相比,用户每次读取此图片时,服务器直接发送给客户就行了. b)   缺点:破坏了原始图 ...