Svelte:有没有一种方法可以缓存 api 结果,从而不会在每次组件呈现时都触发 api 调用?

Svelte: is there a way to cache the api result in a way that it won't trigger the api call everytime the component renders?

可能是我在 Google 中输入了错误的内容,无法得到好的答案。

是否有一种“推荐的精巧”方法来存储 GET 结果的值,以便在每次刷新或 link 切换时,存储中的结果在组件中使用,直到超时(再次调用 api 的地方)?

我的目的是从外部获取博文 api 并将它们显示在列表中但不是在每次刷新时显示,或者 link 切换

我的代码:

<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 获取帖子数据并保存在商店中。然后在进一步的页面安装中使用帖子数据。每当您想刷新数据时,将超时设置为 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}