Search code examples
fetchcomponentssveltekit

Fetched data in child component does not update on page change


I have a page: src/routes/[pageid]/+page.svelte and a file src/routes/[pageid]/page.js

The page.js fetches data from an API and shows correctly on +page.svelte.

Inside +page.svelte I have another component src/components/pagesection.svelte

The [pageid]/+page.svelte page loops over that PageSection component and passes the {section} as a data attribute.

When I change the page (which is dynamic). The {section} in the child component does not update.

+page.svelte

import PageSection from '../../components/PageSection.svelte';

export let data;
$: ({pageData} = data);


{#if pageData}

  <h1>{pageData[0].attributes.Title}</h1>

  {#each pageData[0].attributes.sections.data as section}
    <!-- this updates here -->
    <h4>Section ID: {section.id}</h4>

    <!-- but not in here-->
    <PageSection data={section} />
  {/each}

{/if}

PageSection.svelte

import { onMount } from 'svelte';
import {ApiUrl} from '../stores.js';

export let data;

let SectionID = data.id;
const SectionApiURL = `${ApiUrl}/api/sections/${SectionID}populate=article`;
let sectionDetails;

onMount(() => {
  fetch(SectionApiURL)
  .then(response => {
       if (response.ok) {
          return response.json();
       } else {
          throw new Error('Network response was not ok.');
       }
     })
     .then(data => {
          sectionDetails = data;
      })
     .catch(error => {
        console.error('There was a problem fetching the page data:',error);
  });
});

Any help would be so appreciated. This seems like it should be such a basic thing to do for any website but I have spent hours trying to find out how to get the page information to change inside the component.

Thank you in advance


Solution

  • Your issue is that, inside the PageSection component, you only fetch section details when the component is initially mounted, when what you really want to do is fetch section details whenever the data prop updates.

    You can easily fix this (also, took the opportunity to switch to a more modern async/await syntax):

    import { ApiUrl } from '../stores.js';
    export let data;
    
    $: sectionDetails = updateSection(data) // will run whenever data updates
    
    async function updateSection(section) {
      try {
        const response = await fetch(`${ApiUrl}/api/sections/${section.id}?populate=article`);
        if (!response.ok) {
          throw new Error('Network response was not ok.');
        }
        return response.json();
      } catch (error) {
        console.error('There was a problem fetching the page data:', error);
      }
    }