当前位置:网站首页>Use cache to reduce network requests

Use cache to reduce network requests

2022-06-11 11:48:00 Bolodin's Pineapple

Let's talk about the background first , In a dynamic form , The customer tag data comes from the server , Each time you add an item , The client tag component will request the server to obtain the list of tags to be , When you add items frequently, you will send network requests frequently

How to reduce network requests ? The general idea is to cache the acquired data locally , To be used later , To keep the data fresh , You can set a reasonable “ Shelf life ”, When the cache expires, re request the latest data . Here's the picture

Let's write a pseudocode

function A (){
  // .... 
  // ....
  function getData(){
    // get data , And set the cache 
  }
  useEffect(()=>{
    //  If you have a cache 
    if(xx){
      //  Judge whether it is overdue 
      //  If expired, request 
      getData();
    }else{
      //  If there is no cache, request 
      getData();
    }
  },[]);
}
 Copy code 

It feels good to see it like this , We have basically realized the functions we want , But there's a problem , In each component, you need to write a piece of code to update the cache , We also need to extract the logic for updating the cache , First, design the scheme , We need three basic elements :

  1. Request function
  2. Cache the corresponding key, For read and write caching
  3. Cache lifetime

According to the above ideas and the three elements , I wrote a version React Cache Hook

//  When the same data is used in multiple places , Get data from the server for the first time , Then from SessionStorage Get data in 
import { useEffect } from "react";
import { useSessionStorageState, useRequest } from "ahooks";
const useCache = <T>(api: () => void, key: string, expires = 10000) => {
  const [cache, setCache] = useSessionStorageState<{
    createTime: string,
    data: T
  }>(key);
  const { run, data } = useRequest(api, { manual: true });
  useEffect(() => {
    if (data) {
      setCache({ createTime: new Date().toString(), data: data.data });
    }
  }, [data]);
  useEffect(() => {
    if (cache) {
      const createTime = new Date(cache.createTime || "");
      const time = new Date().getTime() - createTime.getTime();
      if (time > expires) {
        run();
      }
    } else {
      run();
    }
  }, []);
  return [cache?.data];
};
export default useCache;
 Copy code 

The call is simple

import useCache from "@/hooks/useCache";
//...
const index = (props: Props) => {
  const [list] = useCache<Array<Tag>>(getTagList, "customerTags");
}
//...
export default index;
 Copy code 
原网站

版权声明
本文为[Bolodin's Pineapple]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111121048512.html