I’ve been hooked on SvelteJS recently. This one-man-army of a JavaScript framework is as attractive and active as it is reactive. In this article, I’d love to introduce you to a few basic features of the framework. In 26 lines of code, I will cover some interesting SvelteJS features: reactive declarations, asynchronous API fetches with promises, as well as a few neat Svelte shorthands.

The code that I am about to show you is one that allows users to fetch open-source photos from an external API by entering a search query into a regular old input field. The API that we are fetching the image from is  an open API by Unsplash — a free resource for open-source images.

Let me start by showing you my code:

<script>
  let searchTerm = '';
  let promise;
  let src = '';
  $: if (searchTerm != '') {
      promise = getPhoto();
  }

  async function getPhoto() {
      let thisSearchTerm = searchTerm;
      const res = await fetch(`https://source.unsplash.com/featured/1600x900/?${searchTerm}`);
      let photoUrl = res.url;
      if (res.ok && thisSearchTerm == searchTerm) {
          src = photoUrl;
      }
  }
</script>
<input type="text" placeholder="dog, car, house" bind:value={searchTerm} />
<img {src} alt="An image generated by searching for {searchTerm}." class:invisible={!src} />
{#await promise}
  <div class="loading"><img src="/loading.gif" alt="Loading..."></div>
{/await}

#javascript #web-development #svelte

How to Make an API call in Svelte
8.85 GEEK