javascript - Svelte:有没有办法以一种不会在每次组件呈现时触发 api 调用的方式缓存 api 结果?

标签 javascript api caching store svelte

可能是我在 Google 中输入了错误的内容,无法得到好的答案。
是否有一种“推荐的”方法来存储 GET 结果的值,以便在每次刷新或链接切换时,在组件中使用存储中的结果,直到超时(再次调用 api)?
我的目的是从外部 api 获取博客文章并将它们显示在列表中,但不是在每次刷新或链接切换时显示
我的代码:

<script>
  let posts = [];

  onMount(async () => {
  const res = await fetch(apiBaseUrl + "/blogposts");
  posts = await res.json();
});
</script>

  {#each posts as post}
    <h5>{post.title}</h5>
  {/each}
在伪代码中我想要什么
if(store.blogposts.timeout === true){
  onMount(...);
  //renew component
} 

最佳答案

您可以使用商店来实现这一点。初始页面加载从 api 获取帖子数据并保存在商店中。然后在进一步的页面装载中使用帖子数据。每当您要刷新数据时,请将 timeout 设置为 true。
./stores.js

import {writable} from 'svelte/store';
export const posts = writable([]);
export const timeout = writable(false);
./posts.svelte
<script>
import {posts, timeout} from "./stores.js"

 onMount(async () => {
   if($posts.length<1 || $timeout == true){
     const res = await fetch(apiBaseUrl + "/blogposts");
     $posts = await res.json();
   }
});
</script>

  {#each $posts as post}
    <h5>{post.title}</h5>
  {/each}
当您刷新页面时,商店中的帖子将被清除。为了避免这种情况,请使用 localstorage 来缓存数据。请检查以下代码。
./posts.svelte
<script>
let posts = [];
 
onMount(async () => { 
 posts = await getdata();
 } 
 
const getdata = async ()=>{
  // set cache lifetime in seconds
  var cachelife = 5000; 
   //get cached data from local storage
    var cacheddata = localStorage.getItem('posts'); 
    if(cacheddata){
     cacheddata = JSON.parse(cacheddata);
     var expired = parseInt(Date.now() / 1000) - cacheddata.cachetime > cachelife;
      }
    //If cached data available and not expired return them. 
    if (cacheddata  && !expired){
     return cacheddata.posts;
    }else{
    //otherwise fetch data from api then save the data in localstorage 
     const res = await fetch(apiBaseUrl + "/blogposts");
     var posts = await res.json();
     var json = {data: posts, cachetime: parseInt(Date.now() / 1000)}
     localStorage.setItem('posts', JSON.stringify(json));
     return posts;
    }
  }
 
{#each posts as post}
<h5>{post.title}</h5>
{/each}
    

关于javascript - Svelte:有没有办法以一种不会在每次组件呈现时触发 api 调用的方式缓存 api 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64092593/

相关文章:

memory - 判断内存位置是否在 CPU 缓存中

css - 在grails应用程序中缓存包含Css和js文件的 Assets

css - 如果不使用,浏览器会缓存 CSS 背景图像吗?

rest - 如何保护 flask 上的 REST Api

python - 如何通过 python API 将 json/pickle 文件转储和读取到 Google Drive?

api - GitHub API : Get email addresses of all members of organization

javascript - JS : how to delay or set an Interval in a for-loop?

javascript - 为什么递归后事件参数会被遗忘?

javascript - 笔记功能、换行符和无内容

javascript - jQuery Document ready 在动态插入的脚本中如何表现?