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:
- 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. 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)); }
- 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!