Search code examples
svelte

How to make a fetch request everytime a prop changes in a component in Svelte?


Script part of a simple component, this component receives an id from its parent which triggers a fetch request based on that id. Problem here is that the component only mounts once and therefore, whenever a new prop is passed, there is no change. What is the best way to handle this situation?

  import request from "@src/modules/request"; //not important, performs a GET request
  export let channelId;
  let streams = [];

  onMount(async()=>{
    const response = await request({
      url: `/streams?channel_id=${channelId}`,
    });
    streams = response.streams;
  })

What I tried: using beforeUpdate but that resulted in multiple calls which was unncessary.


Solution

  • You can try a reactive declaration, like:

      $: {
        const response = await request({
          url: `/streams?channel_id=${channelId}`,
        });
    
        streams = response.streams;
      }