Fetch In The Browser#
Use fetch(...) in a Svelte script when JSON data should load in the browser:
<script> const reviews = fetch("https://api.example.com/reviews");</script>{{ reviews }} {{ loading }} <p>Loading reviews...</p> {{ /loading }} {{ fail }} <p>Could not load reviews.</p> {{ /fail }} {{ success }} {{ items }} <article> <h2>{{ title }}</h2> </article> {{ /items }} {{ /success }}{{ /reviews }}TemplateX turns const reviews = fetch(...) into Svelte state:
| Value | Meaning |
|---|---|
reviews | The JSON response. |
reviews_loading | true while the request is loading. |
reviews_error | The request error, or null. |
Inside {{ success }}, value tags read from the fetched JSON object.
Use Native Svelte Markup#
The same state can be read with native Svelte syntax:
<script> const joke = fetch("https://official-joke-api.appspot.com/random_joke");</script>{#if joke_loading} <p>Loading joke...</p>{:else if joke_error} <p>Could not load joke.</p>{:else} <article> <h2>{joke.setup}</h2> <p>{joke.punchline}</p> </article>{/if}Use window.fetch(...) when you want the browser's native fetch promise and do not want TemplateX to create loading state.
Use WordPress Values In URLs#
Script fetch URLs can include TemplateX values:
<script> const movie = fetch( "https://api.example.com/movie?t={{ title | lower | urlencode }}", );</script>TemplateX evaluates {{ title | lower | urlencode }} with WordPress, passes the value into the island, and uses it in the browser request URL.
Fetch And Cache On The Server#
Use fetch.static(...) when the JSON should be fetched and cached on the server:
<script> const movie = fetch.static( "https://api.example.com/movie?t={{ title | lower | urlencode }}", ); const plot = movie.Plot;</script>{{ movie }} {{ fail }} <p>Could not load movie data.</p> {{ /fail }} {{ success }} <article> <h2>{{ Title }}</h2> <p>{{ Year }}</p> </article> {{ /success }}{{ /movie }}<p>{{ plot }}</p>Static script fetches do not run fetch() in the browser. TemplateX reads the JSON through WordPress and passes the cached value into the island.
See Script Fetch for the deeper fetch guide.