nuc*_*kle 9 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}
Run Code Online (Sandbox Code Playgroud)
在伪代码中我想要的是:
if (store.blogposts.timeout === true){
onMount(...);
// renew component
}
Run Code Online (Sandbox Code Playgroud)
dag*_*lti 14
您可以使用商店来实现这一目标。初始页面加载从 api 获取帖子数据并保存在商店中。然后在进一步的页面安装中使用帖子数据。每当您想要刷新数据时,请将超时设置为 true。
./stores.js
import {writable} from 'svelte/store';
export const posts = writable([]);
export const timeout = writable(false);
Run Code Online (Sandbox Code Playgroud)
./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}
Run Code Online (Sandbox Code Playgroud)
当您刷新页面时,商店中的帖子将被清除。为了避免这种情况,请使用本地存储来缓存数据。请检查下面的代码。./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}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9641 次 |
最近记录: |