Skip to content

Instantly share code, notes, and snippets.

@helabenkhalfallah
Last active April 10, 2024 20:01
Show Gist options
  • Select an option

  • Save helabenkhalfallah/0b1e9c20d82e69bff5bec1b9339cecc3 to your computer and use it in GitHub Desktop.

Select an option

Save helabenkhalfallah/0b1e9c20d82e69bff5bec1b9339cecc3 to your computer and use it in GitHub Desktop.
Using external Api
<!-- Import the fetchData function from the api.js file -->
<script>
import { onMount } from 'svelte'; // Import the onMount function from Svelte
import { fetchData } from './api'; // Import the fetchData function from the api.js file
let responseData; // Declare a variable to store the fetched data
// Make an HTTP GET request when the component mounts
onMount(async () => {
try {
// Call the fetchData function to fetch data from the API
responseData = await fetchData();
} catch (error) {
// Handle the error if needed
}
});
</script>
<!-- Conditional rendering based on the availability of responseData -->
{#if responseData}
<!-- Display the fetched data -->
<p>{JSON.stringify(responseData)}</p>
{:else}
<!-- Show a loading message while data is being fetched -->
<p>Loading...</p>
{/if}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment