0

I am working on online shop. I have an order reducer, where I can hold my order. After page refreshing my store becomes empty (which is obvious). The main idea is to have my order saved for some period of time (e.g, 20 mins). Also, I want to save only piece of my store (order state). So, I decided to persist my state to localstorage

But here is a trick. How to do it correctly from architecture and patterns side? I have a few ideas:

  1. Subscribe to my store using store.subscribe() and rewrite my localstorage on every store change. It will be a bit strange, because I need to parse my store using, take a piece of it and push to localstorage. Also, my callback will be called on every change, it may affect productivity.
  2. Do it right in the dispatcher (this is an anti-pattern I suppose):

    const addToOrder = orderItem => ({ type: actionTypes.ADD_TO_ORDER, payload: orderItem }); export const addItemToOrder = orderItem => dispatch => { // localstorage.setItem() ... dispatch(addToOrder(orderItem)); }

  3. Use libraries like
    https://www.npmjs.com/package/redux-persist
    https://www.npmjs.com/package/redux-localstorage
    https://www.npmjs.com/package/redux-localstorage-simple
    But in this case, how to clear my localstorage in 20 minutes after closing tab?

So, how to persist my state correctly and how to clear localstorage ins some time?
Thank you in advance for your help!

1 Answers1

0

All ways are possible. Second also, as you use action creator to do additional work. For example action creators are used for data fetching, so storing data to localStore is not a problem.

I suggest to use option 3. It provides best separation of concerns. Code for storing data is located in single place and to spread over several action creators.

Unfortunately, you'll not be able to set expiration time for localStore items. But as localStore is accessed only by your app, you may leave items forever, but adding storage date/time. And during app start next time just check time and if data more than 20 min old, purge it. You can do this check in config.merge function.

Fyodor Yemelyanenko
  • 11,264
  • 1
  • 30
  • 38
  • Yeah, I decided to use `redux-persist` library and now I can save my store. But also, I found out that was added ability to reset store after some timeout: https://github.com/rt2zz/redux-persist/pull/702/files. But still I can"t implement it... :( I have tried different variants: https://stackoverflow.com/questions/56871364/redux-persist-reset-persisted-store-after-timeout – Yaroslav Melnychuk Jul 03 '19 at 13:34