Created
April 10, 2024 19:58
-
-
Save helabenkhalfallah/20c00173d69d2f723a908aa929f85893 to your computer and use it in GitHub Desktop.
Get HTTP Service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!-- This Svelte component fetches data from an API when it mounts and displays the response data or a loading message accordingly. --> | |
| <script> | |
| // Import the 'onMount' function from Svelte for executing code when the component mounts | |
| import { onMount } from 'svelte'; | |
| // Import axios for making HTTP requests | |
| import axios from 'axios'; | |
| // Declare a variable to store the response data | |
| let responseData; | |
| // Use the 'onMount' function to execute code when the component mounts | |
| onMount(async () => { | |
| try { | |
| // Make an HTTP GET request to fetch data from the API | |
| const response = await axios.get('https://api.example.com/data'); | |
| // Store the response data in the 'responseData' variable | |
| responseData = response.data; | |
| } catch (error) { | |
| // Log an error message if there's an error fetching data | |
| console.error('Error fetching data:', error.message); | |
| } | |
| }); | |
| </script> | |
| {#if responseData} | |
| <!-- If response data is available, display it --> | |
| <p>{JSON.stringify(responseData)}</p> | |
| {:else} | |
| <!-- If response data is not available yet, show a loading message --> | |
| <p>Loading...</p> | |
| {/if} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment