DEV Community

Stefan Midjich
Stefan Midjich

Posted on

Cannot get onMount to work with API

Maybe I'm misunderstanding how onMount works but I can see that the API is requested, it works, offers list is populated, I can output it to console.log, but the template never shows the OfferCard component, it stays on Loader as if the offers list is empty.

<script>
  import { onMount } from 'svelte';
  import Navigation from '$lib/Navigation.svelte';
  import OfferCard from '$lib/OfferCard.svelte';
  import Loader from '$lib/Loader.svelte';
  let offers = []

  async function getOffers(store) {
    const url = `http://localhost:8000/offers/${store}`;
    try {
      const response = await fetch(url);
      if (response.ok) {
        return response.json();
      } else {
        throw new Error(`Response status: ${response.status}`);
      }
    } catch (error) {
      console.error(error.message);
    }
  }

  onMount(async () => {
    offers.push(...await getOffers('ica'));
    //console.log(offers)
  });
</script>

<section class="section">
  <div class="container">
    <Navigation />

    {#each offers as offer }
      <OfferCard title={offer.title} imageUrl={offer.url} />
    {:else}
      <Loader />
    {/each}
  </div>
</section>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)