[Redux] Persisting the State to the Local Storage
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的更多相关文章
- [MST] Store Store in Local Storage
For an optimal user and developer experience, storing state in local storage is often a must. In thi ...
- Ionic2学习笔记(8):Local Storage& SQLite
作者:Grey 原文地址: http://www.cnblogs.com/greyzeng/p/5557947.html Ionic2可以有两种方式来存储数据,Local S ...
- Web持久化存储Web SQL、Local Storage、Cookies(常用)
在浏览器客户端记录一些信息,有三种常用的Web数据持久化存储的方式,分别是Web SQL.Local Storage.Cookies. Web SQL 作为html5本地数据库,可通过一套API来操纵 ...
- cookie ,session Storage, local storage
先来定义: cookie:是网站为了标识用户身份存储在本地终端的数据,其数据始终在APP请求中存在,会在服务器和浏览器中来回传递 数据大小不超过4k, 可以设置有效期,过了有效期自动删除 sessio ...
- Session,Cookie 和local storage的区别
以前从没有听说过local storage, 在网上查了一些资料,得到如下结论 从存储位置看,分为服务器端存储和客户端存储两种 服务器端: session 浏览器端: cookie, localSto ...
- 关于local storage及session storage 应用问题
H5- storage 可以在不同页面内进行数据传递数据信息,保证了数据传输不许后台交互即可在前端部分自我实现,以下为local storage 应用个人简析: * localStorage * se ...
- 关于local storage 和 session storage以及cookie 区别简析
session storage 和local storage 都是存储在客户端的浏览器内: 一:关于COOKIE 的缺陷 * Cookie的问题 * 数据存储都是以明文(未加密)方式进行存储 * 安全 ...
- local storage 简单应用‘’记住密码’
前些时候一直用cookie等来进行登录页面记住面膜操作,但是由于其存储容量小等缘故,所以后来转向local storage,原理为:当用户勾选记住密码时,local storage 存储用户名密码同时 ...
- web页面缓存技术之Local Storage
业务:检测页面文本框的值是否有改变,有的话存入缓存,并存储到数据库,这样用户异常操作后再用浏览器打开网页,就可避免重新填写数据 数据库表:Test,包含字段:PageName,PageValue BL ...
随机推荐
- service httpd restart失败解决方法(小记)
1.首先查看错误日志 /var/log/message看看具体问题.如果一时难以判定直接使用下面一招 2.直接中断http服务,killall -9 httpd, 然后重启http,service ...
- 64位Win7下编译Python3的计算机视觉库:OpenCV
注:本文全原创,作者:Noah Zhang (http://www.cnblogs.com/noahzn/) OpenCV目前最新版是3.0.0 rc1,官方给出了编译好的Python2可以直接使用 ...
- Python学习笔记(一)Python安装及环境变量的配置
1.下载python安装包. 下载地址:https://www.python.org/ 2.配置环境变量 找到python的安装路径.C:\Python27;script的路径:C:\Python27 ...
- jsonp跨域问题记录
这段时间用H5做移动app开发,遇到不少之前做web的时候不曾遇到的问题,记录一下,共勉-- 首先说一个:js跨域取数的问题 描述: 之前做web都是通过后台获取数据,没考虑过跨域的问题.这次用h5 ...
- bzoj 1034: [ZJOI2008]泡泡堂BNB 貪心
1034: [ZJOI2008]泡泡堂BNB Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 1398 Solved: 727[Submit][Sta ...
- Gradle在大型Java项目上的应用
在Java构建工具的世界里,先有了Ant,然后有了Maven.Maven的CoC[1].依赖管理以及项目构建规则重用性等特点,让Maven几乎成为Java构建工具的事实标准.然而,冗余的依赖管理配置. ...
- 【POJ2699】The Maximum Number of Strong Kings(网络流)
Description A tournament can be represented by a complete graph in which each vertex denotes a playe ...
- Keil工程文件的建立、设置与目标文件的获得
单片机开发中除必要的硬件外,同样离不开软件,我们写的汇编语言源程序要变为 CPU 可以执行的机器码有两种方法,一种是手工汇编,另一种是机器汇编,目前已极少使用手工 汇编的方法了.机器汇编是通过汇编软件 ...
- SQL servere 范式、事务
一.数据库范式: 1.构造数据库必须遵循一定的规则.在关系数据库中,这种规则就是范式. 范式是符合某一种级别的关系模式的集合.数据库中的关系必须满足一定的要求,即满足不同的范式. 满足最低要求的范式是 ...
- [性能分析]linux文件描述符(转)
1.什么是文件和文件描述符 Linux中文件可以分为4种:普通文件.目录文件.链接文件和设备文件.1.普通文件是用户日常使用最多的文件,包括文本文件.shell脚本.二进制的可执行和各种类型的数据.l ...