tippexx
tippexx

Reputation: 95

Sapper/Svelte - How to fetch periodically

How would I periodically fetch data using Sapper?

Is this the correct way?

//src/routes/fetch_on_this_page.svelte

<script>
  setInterval(async () => {
    //fetch here
  }, 3000);
</script>

Upvotes: 2

Views: 4046

Answers (2)

Rich Harris
Rich Harris

Reputation: 29615

The neatest way to do this is to do it all inside onMount:

<script>
  import { onMount } from 'svelte';

  onMount(() => {
    async function fetchData() {...}
    
    const interval = setInterval(fetchData, 3000);
    fetchData();

    return () => clearInterval(interval);
  });
</script>

Aside from creating fewer component-level variables, onMount code doesn't run in during server-side rendering, so involves less work. If you needed to do this in multiple components you could also wrap this up into a custom lifecycle function:

// poll.js
import { onMount } from 'svelte';

export function poll(fn, ms) {
  onMount(() => {
    const interval = setInterval(fn, ms);
    fn();

    return () => clearInterval(interval);
  });
}
<script>
  import { poll } from './poll.js';

  poll(async function fetchData() {
    // your implementation goes here
  }, 3000);
</script>

Upvotes: 9

tippexx
tippexx

Reputation: 95

<script>
  import { onMount, onDestroy } from "svelte";

  async function fetchData() {
  //Fetch
  }

  const interval = setInterval(async () => {
    fetchData();
  }, 3000);

  onMount(async () => {
    fetchData();
  });

  onDestroy(() => clearInterval(interval));
</script>

https://svelte.dev/tutorial/ondestroy

Upvotes: 3

Related Questions