How do I implement caching in Redux?

前端 未结 6 2114
难免孤独
难免孤独 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:49

    I'm assuming you are using async actions to handle your API calls.

    This is the place where I would put the caching logic, which results in a nice encapsulation:

    export function fetchData(url) {   
        return function (dispatch) {
            dispatch(requestData(url))
    
            if (isCached(url)) {
                const cachedData = getCached(url)
                dispatch(receiveData(url, cachedData))
            } else {
                return fetch(url)
                  .then(response => response.json())
                  .then(json => {
                      dispatch(receiveData(url, json))
                      setCached(url, json)
                  })
            }
        }
    }
    

    Implementing isCached, getCached and setCached for your local storage should be rather straightforward.

提交回复
热议问题