最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - SapperSvelte - How to fetch periodically - Stack Overflow

programmeradmin0浏览0评论

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>

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>
Share Improve this question asked May 18, 2020 at 15:26 tippexxtippexx 951 silver badge7 bronze badges 1
  • 1 I don't understand the issue. You could of course use setInterval, you would probably want to clear it on ponent destroy. – J Dubuis Commented May 18, 2020 at 15:46
Add a ment  | 

2 Answers 2

Reset to default 9

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 ponent-level variables, onMount code doesn't run in during server-side rendering, so involves less work. If you needed to do this in multiple ponents 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>
<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

发布评论

评论列表(0)

  1. 暂无评论