Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 340
Yousuf Iqbal Hashim Avatar asked Oct 29 '19 09:10

Yousuf Iqbal Hashim


1 Answers

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

like image 86
Lyzard Kyng Avatar answered Jan 04 '23 02:01

Lyzard Kyng