[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 ...
随机推荐
- 使用Express搭建服务器
Express是基于Node.js平台,快速.开放.极简的web开发框架.所以,使用Express之前,请确保已安装Node.js. 1.创建一个目录作为当前工作目录: $ mkdir myapp $ ...
- UI图标不用愁:矢量字体图标Font-Awesome
Font-Awesome,这个项目主要是css3的一个应用,准确的说是一段css,这里的把很多图标的东西做到了font文件里面,然后通过引用外部font文件的方式,来展现图标. Font Awesom ...
- C# 数据结构 栈 Stack
栈和队列是非常重要的两种数据结构,栈和队列也是线性结构,线性表.栈和队列这三种数据结构的数据元素和元素的逻辑关系也相同 差别在于:线性表的操作不受限制,栈和队列操作受限制(遵循一定的原则),因此栈和队 ...
- iOS 实现脉冲雷达以及动态增减元素 By Swift-感谢分享
Swift经过Xcode6 Beta4一版更新后,基本上已经可以作为生产工具了,虽然有一些地方和ObjC比起来要“落后”一些,但也无伤大雅.这里就用Xcode6 Beta4+iOS SDK 8.0开发 ...
- 转:实用 .htaccess 用法大全
原文来自于:http://www.techug.com/htaccess-snippets 这里收集的是各种实用的 .htaccess 代码片段,你能想到的用法几乎全在这里. 免责声明: 虽然将这些代 ...
- tyvj P1716 - 上帝造题的七分钟 二维树状数组区间查询及修改 二维线段树
P1716 - 上帝造题的七分钟 From Riatre Normal (OI)总时限:50s 内存限制:128MB 代码长度限制:64KB 背景 Background 裸体就意味着 ...
- ios7控件特性(一)
苹果发布iOS7之后,iOS7全部采用扁平化的界面,我们的app界面在iOS7上出现了很大的改变,这包括UINavigationBar,UIButton,UIActionSheet,UITabBar等 ...
- 纯CSS实现delay连续动画
从前css3还没出来的时候,用jquery的delay方法可以串起一个一个独立的动画片段. 那么在不使用jquery的平台上,如何借助css3来完成一些列动作呢? 有高人做了一个动感十足的人物动画: ...
- 截断WM_SYSCOMMAND的SC_CLOSE命令(VC与Delphi双版本)
WM_SYSCOMMAND - 系统命令消息,当点击最大化按钮,最小化按钮,关闭按钮等.都会收到这个消息.常用于窗口关闭时提示用户处理.WPARAM - 具体的命令,例如 关闭 SC_CLOSELPA ...
- 深入剖析Java中的装箱和拆箱(转)
自动装箱和拆箱问题是Java中一个老生常谈的问题了,今天我们就来一些看一下装箱和拆箱中的若干问题.本文先讲述装箱和拆箱最基本的东西,再来看一下面试笔试中经常遇到的与装箱.拆箱相关的问题. 以下是本文的 ...