Yousuf Iqbal Hashim
Yousuf Iqbal Hashim

Reputation: 975

How to fetch data before component mount in Svelte?

Unlike onMount there is no beforeMount lifecycle event in SvelteJS. So, how do we fetch data that the page depends on before mounting? onMount fetches produces glitches. One can say that I can wrap dependent DOM inside if conditions. But I don't think it is the right solution. Very like in Sapper there is a preload function that can load page dependent data before mounting. What is the alternative to this (Sapper's preload) behavior in SvelteJS?

Upvotes: 9

Views: 14727

Answers (3)

Bob Fanger
Bob Fanger

Reputation: 29897

You'd create another component that doesn't render the Component until the data is ready.

<script>
import Post from "./Post.svelte";

const url = 'https://jsonplaceholder.typicode.com/posts/1';
const promise = fetch(url).then(response => response.json());
</script>

{#await promise then data}
    <Post title={data.title} />
{/await}

REPL

Depending on the scenario you can use a router that has data loading supports, like the sveltekit router.

Upvotes: 4

dudino
dudino

Reputation: 31

Noob here, to your sub-question: isnt svelte front end only? Meaning no SSR support and thus no option for preloading data with first user request.

Since, you dont have any server that would preload your data and give the user prepacked front-end (svelte pages) with data. Thus, you need sapper to provide a functionality where server can fetch data with first user request, populate front end and send it to user.. This way, user receives svelte pages, populated with data, upon first response from your server.

Since you use only svelte, user needs to contact your server more often.. First, it fetches the front-end, then front-end fetches data from back-end. Furthermore, it aint SEO friendly as robots dont wait for the subsequent server responses. Thus, your pages wont be analyzed properly as robots analyze 'blank'page, no data mounted yet, and move to next, before response can be processed.

Please, correct me If I am wrong ;)

I believe above answer is right: 1. create empty variable in script tag 2. add below onMount call and fetch data from serverto above declared variable 3. check if var is empty and show loading button 4. if var isnt empty, then show user content 6. profit?

P.S: Sorry for any misconceptions or bad English :)

Upvotes: 2

Lyzard Kyng
Lyzard Kyng

Reputation: 1568

You can put the fetch code right under <script> tag

A <script> block contains JavaScript that runs when a component instance is created.

There is also context="module" attribute with <script> tag. It

runs once when the module first evaluates, rather than for each component instance

See the official docs

Upvotes: 3

Related Questions