微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Svelte:有没有一种方法可以缓存api结果,使得它不会在每次组件渲染时都触发api调用?

如何解决Svelte:有没有一种方法可以缓存api结果,使得它不会在每次组件渲染时都触发api调用?

可能是因为我在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的数据并保存在商店中。然后在更多页面安装中使用posts数据。每当您要刷新数据时,请将超时设置为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}
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。