REDUX-PERSIST LÀ GÌ

  -  

Redux persist is a library allowing to save the redux store in the local storage of your browser.

Bạn đang xem: Redux-persist là gì

But, using redux-persist and changing the store"s architecture could trigger issues. This article illustrates, with a basic example, how persistence works with your Redux store, then focus on the persisted store"s transformation across code versions & tiện ích uses.

To install it in your project, I recommend you read the documentation or this article.

How to lớn persist a store & how it works

Let"s take, as an example, this redux store from a React project, generated with create-react-app:


*

There is:

a debounced input with current value = inputValuea button GO submitting inputValue in store as key confirmedMessagea persisted field named number in redux counting the number of submissions made.

I implemented redux-persist as explained in the official doc and my store. You can find all the code in this repo.


*

There is a custom function persist(), to define in persistConfig only what"s changed for this article.

Steps of persistence:

Persistence with Redux-persist occurs in 3 mains steps. To show it, i useRedux devTools chrome extension : INIT, PERSIST và REHYDRATE.

Xem thêm: Trán Cao Mặt Tròn Để Tóc Gì Nữ, Tóc Ngắn Cho Mặt Tròn Trán Cao

"
INIT":

While visiting the phầm mềm, the redux store is created as the initial state given through the reducers. This defines the first content of your ứng dụng, and persistence has not done its job yet.


*

During persist step, in every persisted store, an object is added with this configuration:


*

*

*

INIT: initial state set the khung I need

persist/PERSIST: _persist object is added with rehydrated false

persist/REHYDRATE: persisted data replace the Redux store.


*

What went wrong here?

The variable "number", which is supposed khổng lồ have sầu the structure of the new version of the phầm mềm, is replaced by the old persisted structure. You lose all your store changes.


This inconsistency can jeopardize the use of your code if you don"t anticipate them.

Handling it with a version-controlled store.

Redux-persist allows you to lớn transform your store depending on the version you want for the app: you can control the version of your store.

Xem thêm: Gà Sao Làm Món Gì Ngon - Các Món Ăn Từ Thịt Gà Sao

To bởi vì this, use the function createMigrate() và pass in the persistConfig object in migrate" key:


Migrations are applied on your state before replacing your store data in REHYDRATE step.

If your storage comes from the store in version -1, which is the default version, and you deploy version 0 in your tiện ích, the migration 0 will be applied on storage state at every user"s connexion:


For example, with this definition of the passed migrations, your state will be rephối as the initial state & you will have sầu the expected behaviour during REHYDRATE: