Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching in React

In my react App I have a input element. The search query should be memoized, which means that if the user has previously searched for 'John' and the API has provided me valid results for that query, then next time when the user types 'Joh', there should be suggestion for the user with the previously memoized values(in this case 'John' would be suggested).

I am new to react and am trying caching for the first time.I read a few articles but couldn't implement the desired functionality.

like image 903
shinite Avatar asked Feb 14 '17 12:02

shinite


People also ask

What is caching in React?

Caching is a technique that helps us to stores a copy of a given resource into our browser and serves it back when requested. 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.

How do I cache data in ReactJS?

Approach: Follow these simple steps in order to store multiple cache data in ReactJS. We have created our addMultipleCacheData function which takes the user data list 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.

Can you cache React components?

React Component Caching provides its own cache implementation as well as support for Redis and Memcached. Simply create your preferred cache and pass it into one of the rendering methods.

Is Redux caching?

When data is fetched from the server, RTK Query will store the data in the Redux store as a 'cache'. When an additional request is performed for the same data, RTK Query will provide the existing cached data rather than sending an additional request to the server.


2 Answers

You don't clarify which API you're using nor which stack; the solution would vary somewhat depending on if you are using XHR requests or something over GraphQL.

For an asynchronous XHR request to some backend API, I would do something like the example below.

Query the API for the search term

_queryUserXHR = (searchTxt) => {
  jQuery.ajax({
    type: "GET",
    url: url,
    data: searchTxt,
    success: (data) => {
      this.setState({previousQueries: this.state.previousQueries.concat([searchTxt])
    }
  });
}

You would run this function whenever you want to do the check against your API. If the API can find the search string you query, then insert that data into a local state array variable (previousQueries in my example).

You can either return the data to be inserted from the database if there are unknowns to your view (e.g database id). Above I just insert the searchTxt which is what we send in to the function based on what the user typed in the input-field. The choice is yours here.

Get suggestions for previously searched terms

I would start by adding an input field that runs a function on the onKeyPress event:

<input type="text" onKeyPress={this._getSuggestions} />

then the function would be something like:

_getSuggestions = (e) => {
  let inputValue = e.target.value;
  let {previousQueries} = this.state;
  let results = [];
  previousQueries.forEach((q) => {
    if (q.toString().indexOf(inputValue)>-1) {
      result.push(a);
    }
  }
  this.setState({suggestions: results});
}

Then you can output this.state.suggestions somewhere and add behavior there. Perhaps some keyboard navigation or something. There are many different ways to implement how the results are displayed and how you would select one.

Note: I haven't tested the code above

like image 199
Chris Avatar answered Oct 01 '22 22:10

Chris


I guess you have somewhere a function that queries the server, such as

const queryServer = function(queryString) {
  /* access the server */
}

The trick would be to memorize this core function only, so that your UI thinks its actually accessing the server.

In javascript it is very easy to implement your own memorization decorator, but you could use existing ones. For example, lru-memoize looks popular on npm. You use it this way:

const memoize = require('lru-memoize')
const queryServer_memoized = memoize(100)(queryServer)

This code keeps in memory the last 100 request results. Next, in your code, you call queryServer_memoized instead of queryServer.

like image 42
Antoine Trouve Avatar answered Oct 01 '22 22:10

Antoine Trouve