0

I have a component that accesses a svelte store writable but the component just gets rendered before the data arrives into the store variable.

This are the errors enter image description here

I want this component to start rendering when there is some data in currentOneCallData.

<script>
  import { onDestroy, onMount } from "svelte";
  import rain from "../assets/icons/d-rain.png";
  import { currentOneCallData } from "../cli";

  let unsubscribe;
  let loading = true;

  onMount(() => {
    unsubscribe = currentOneCallData.subscribe(value => {
      if(value !== undefined){
        loading = false;
        unsubscribe();
      }
    })
  })

  onDestroy(() => {
    if(unsubscribe) {
      unsubscribe(); 
    }
  });

  function convertUnixTimestamp(timestamp) {
    const months = [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec",
    ];
    const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

    // Convert timestamp to milliseconds
    const date = new Date(timestamp * 1000);

    // Extract day, month, and date
    const day = days[date.getDay()];
    const month = months[date.getMonth()];
    const dayOfMonth = date.getDate();

    // Concatenate and return formatted date
    return `${day}, ${month} ${dayOfMonth}`;
  }
</script>

I have also implemented conditional logic that prevents it from accessing data from object before its available.

{#if !loading}
  <div class="current-container">
    <div class="text-content">
      <div class="dateAndTime">
        <p class="date">{convertUnixTimestamp($currentOneCallData.current.dt)}</p>
        <p class="time">7:40 AM</p>
      </div>
      <p class="temp">{$currentOneCallData.current.temp}<sup class="temp-unit">°C</sup></p>
      <h4 class="feel-container">
        Feels like <span class="feel"
          >{$currentOneCallData.current.feels_like} <span class="temp-unit">°C</span></span
        >
      </h4>
      <h3 class="desc">{$currentOneCallData.current.weather[0].description}</h3>
    </div>
    <div class="icon-container">
      <img src={rain} alt="" class="icon" />
    </div>
  </div>
{:else}
  <div class="loading"><p>Loading...</p></div>
{/if}

2
  • Please do not upload images of code/data/errors. Commented Apr 7, 2024 at 14:48
  • You don't need subscribe in components, there is extra $store syntax which can be combined with reactive statements $: . You also can return a destroy function from onMount, there rarely is a reason to use onDestroy directly. Commented Apr 7, 2024 at 14:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.