Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache API response and use it later in react & redux?

In my React based application, there is a rest API call which fetches all the data in one shot which is needed for the whole page. The response has data which can be used in a population of dropdowns as well. But I am not sure how this can be achieved. I am currently making a new request whenever the drop-down value is selected. Please do suggest me how to do implement it efficiently without making multiple unwanted rest calls.

like image 213
A srinivas Avatar asked Oct 20 '17 04:10

A srinivas


People also ask

Can API response be cached?

Caching in REST APIs POST requests are not cacheable by default but can be made cacheable if either an Expires header or a Cache-Control header with a directive, to explicitly allows caching, is added to the response. Responses to PUT and DELETE requests are not cacheable at all.

How do you implement caching in ReactJS?

Approach: Follow these simple steps in order to store single data into cache in ReactJS. We have created our addDataIntoCache function which takes the user data and store into the browser cache. When we click on the button, the function is triggered and data gets stored into the cache, and we see an alert popup.

How do I cache a rest response?

Full Stack Java developer - Java + JSP + Restful WS + Spring Caching refers to storing the server response in the client itself, so that a client need not make a server request for the same resource again and again.


1 Answers

you can cache in HDD or RAM.

  • HDD = e.g. localStorage
  • RAM = application state, e.g. redux store.

For localStorage you can use my little plugin for this: https://www.npmjs.com/package/localstorage-ttl

In app state (RAM) - fire action to fetch data, use redux-thunk, redux-saga or similar to make a call and with reducer save data in the store. Retrieve data from store.

https://github.com/gaearon/redux-thunk https://github.com/redux-saga/redux-saga

like image 161
Lukas Liesis Avatar answered Oct 02 '22 12:10

Lukas Liesis