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?
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.