Inside "onMount" I have fetch API, but I don't want to fetch that API every single time user tap on route on menu-bar is there any solution for that? (beside local storage)
<script>
import { onMount } from "svelte";
let poem = [];
let flag = false;
onMount(async () => {
const response = await fetch(url);
poem = await response.json();
flag = true;
});
</script>
{#if flag}
<pre>{poem.plainText}</pre>
{:else}
<b>Loading...</b>
{/if}
CodePudding user response:
You could put your poem
in a writable
store separate from the component and fetch
it in the browser.
Example
// stores/poem.js
import { browser } from '$app/environment';
import { writable } from 'svelte/store';
export const poem = writable(null);
if (browser) {
fetch(url).then(res => res.json()).then(data => {
poem.set(data);
});
}
<!-- routes/poem/ page.svelte -->
<script>
import { poem } from '$lib/stores/poem';
</script>
{#if $poem}
<pre>{poem.plainText}</pre>
{:else}
<b>Loading...</b>
{/if}