How do I implement caching in Redux?

前端 未结 6 2097
难免孤独
难免孤独 2020-12-24 12:17

I would like to avoid calling an API twice if I already have the data in my store.

How do I do this with Redux?

6条回答
  •  清酒与你
    2020-12-24 12:48

    I came up with the same problem, where I wanted to add a cache layer between my action and reducer. My solution was to create a middleware, to cache the Request action before it goes to the actual thunk, which request data from the API.

    Doing this has a pros that you don't need to modify your existing action and reducer. You just add a middleware. Here is how the middleware look like:

    const cache = store => next => action => {
      // handle FETCH action only
      if (action.type !== 'FETCH') {
        return next(action);
      }
    
      // check if cache is available
      const data = window['__data'];
      if (!data) {
        // forward the call to live middleware
        return next(action);
      }
      return store.dispatch({ type: 'RECEIVE', payload: { data: `${data} (from cache)` } });
    }
    
    export default cache;
    

    Try out the live demo at https://stackblitz.com/edit/redux-cache-middleware or check out my blog post for more info http://www.tonnguyen.com/2018/02/13/web-programming/implement-a-cache-middleware-for-redux/

提交回复
热议问题