svelte

How to trigger/force update a Svelte component


I am trying to get my head around the svelte 3 reactivity thing...

  1. I wanted to force refreshing a UI on a button click. I am using a custom component AsyncFetcher that accepts HTTP post data, and returns data object (http post result) for its slot.

  2. I wanted to have a disable functionality. So when the "Disable" button is clicked an http api is called followed by a refresh of the data view.

<script>
    export let id

    function onDisable() {
        fetch('disable-api-url', {id: id})
        // Then ??
        // What to do after the fetch call, to refresh the view
    }
</script>

<AsyncFetcher postParam={id} let:data>
    {data.name}

    <button on:click={??}>Refresh</button>
    <button on:click={onDisable}>Disable Item</button>
</AsyncFetcher>

I tried doing on:click={() => id=id} to trick it to refresh to no avail. If id would have been an object rather than string id={...id} would have worked, which unfortunately, is not the case here.

What would be a correct way to achieve this?


Solution

  • Using a component to manage fetches is very unconventional. Typically you'd fetch data inside onMount, or in an event handler:

    <script>
      import { onMount } from 'svelte';
    
      let initialData;
      let otherData;
    
      onMount(async () => {
        const res = await fetch('some-url');
        initialData = await res.json();
      });
    
      async function update() {
        const res = await fetch('some-other-url');
        otherData = await res.json();
      }
    </script>
    
    {#if initialData}
      <p>the data is {initialData.something}</p>
    {/if}
    
    <button on:click={update}>update</button>