Introduction to Asynchronous Data in Svelte
Fetching Data from an API
Using the `#await` Block

The #await block in Svelte is used to handle promises and manage the different states of an asynchronous operation: loading, success, and error. The syntax is straightforward and intuitive.

Here’s how we use the #await block in our example:

{#await postPromise}
  <p>Loading post...</p>
{:then post}
  <h2>{post.title}</h2>
  <p>{post.body}</p>
{:catch error}
  <p>Error: {error.message}</p>
{/await}

In this code:

  • The #await postPromise block handles the loading state, displaying a message while the data is being fetched.
  • The :then post block handles the success state, displaying the post’s title and body once the data is fetched.
  • The :catch error block handles the error state, displaying an error message if something goes wrong during the fetch operation.

This structure ensures that the user interface remains responsive and informative throughout the entire process.

Handling User Interaction

To make our component interactive, we’ll add a button that allows the user to load the next post. When the button is clicked, we’ll increment the postId variable, which will trigger a new fetch operation and update the UI.

Here’s the code for the button:

<button onclick={() => postId++}>Load Next Post</button>

When the button is clicked, postId is incremented by 1. Since postId is a reactive variable, the $effect rune will detect the change and trigger a new fetch operation. The #await block will then update the UI to reflect the new data.

Summary and Practice Preparation
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal