* New FAQ, new renderer * Push blog stuff * Fix blog posts * Add tutorial to be rendered * Update documentation/content/blog/2023-03-09-zero-config-type-safety.md Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com> * Update documentation/content/blog/2023-03-09-zero-config-type-safety.md Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com> * Revamp a lot of renderer, make it (soft) compatible with sveltekit * Remove markdown types * Clean up faq +page * Document stuff * Make the options more explicity * chore(site-2): Restructure docs pt 2 (#8604) * Push * Update readme * Push * inor accessibility fix * minr stuff * Add prepare * Run prettier * Remove test script * pnpm update * Update sites/svelte.dev/src/routes/examples/[slug]/+page.svelte Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com> * Update sites/svelte.dev/package.json Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com> --------- Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com> --------- Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
1.3 KiB
title |
---|
onMount |
Every component has a lifecycle that starts when it is created, and ends when it is destroyed. There are a handful of functions that allow you to run code at key moments during that lifecycle.
The one you'll use most frequently is onMount
, which runs after the component is first rendered to the DOM. We briefly encountered it earlier when we needed to interact with a <canvas>
element after it had been rendered.
We'll add an onMount
handler that loads some data over the network:
<script>
import { onMount } from 'svelte';
let photos = [];
onMount(async () => {
const res = await fetch(`/tutorial/api/album`);
photos = await res.json();
});
</script>
It's recommended to put the
fetch
inonMount
rather than at the top level of the<script>
because of server-side rendering (SSR). With the exception ofonDestroy
, lifecycle functions don't run during SSR, which means we can avoid fetching data that should be loaded lazily once the component has been mounted in the DOM.
Lifecycle functions must be called while the component is initialising so that the callback is bound to the component instance — not (say) in a setTimeout
.
If the onMount
callback returns a function, that function will be called when the component is destroyed.