I want to persist some parts of my state tree to the localStorage. What is the appropriate place to do so? Reducer or action?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Reducer is never an appropriate place to do this because reducers should be pure and have no side effects.
I would recommend just doing it in a subscriber:
Before creating the store, read those persisted parts:
If you use
combineReducers()
you’ll notice that reducers that haven’t received the state will “boot up” as normal using their defaultstate
argument value. This can be pretty handy.It is advisable that you debounce your subscriber so you don’t write to localStorage too fast, or you’ll have performance problems.
Finally, you can create a middleware that encapsulates that as an alternative, but I’d start with a subscriber because it’s a simpler solution and does the job well.
In a word: middleware.
Check out redux-persist. Or write your own.
[UPDATE 18 Dec 2016] Edited to remove mention of two similar projects now inactive or deprecated.
If anybody is having any problem with the above solutions, you can write your own to. Let me show you what I did. Ignore
saga middleware
things just focus on two thingslocalStorageMiddleware
andreHydrateStore
method. thelocalStorageMiddleware
pull all theredux state
and puts it inlocal storage
andrehydrateStore
pull all theapplicationState
in local storage if present and puts it inredux store
To fill in the blanks of Dan Abramov's answer you could use
store.subscribe()
like this:Before creating the store, check
localStorage
and parse any JSON under your key like this:You then pass this
peristedState
constant to yourcreateStore
method like this:I cannot answer @Gardezi but an option based on his code could be:
the difference is that we are just saving some actions, you could event use a debounce function to save only the last interaction of your state