javascriptsveltesappersvelte-3

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>

Solution

  • 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>