Summary
Context
Actual behavior (Problem)
Expected behavior
Minimal, Testable, Executable Example
Data
Sources
Notes
Clues
Context
I am trying to get a list of JSON objects from the URL http://localhost:1337/restaurants
using Axios, in a Svelt Webapp. This call is censed to be executed when the Svelte component is initialized, similarly to the Svelte tutorial: https://svelte.dev/tutorial/await-blocks.
Actual behavior (Problem)
When I open the Web page containing the Svelte component, I don't see the network call in my Chromium dev tools network panel.
I can see this error shown in the Web page (obviously thanks to my {:catch}
):
TypeError: Cannot convert undefined or null to object
Expected behavior
When I open the Web page containing the Svelte component, I should see the network call in my Chromium dev tools network panel, and it should show each of the JSON objects in a list item.
Of course, the following error must not be raised:
TypeError: Cannot convert undefined or null to object
Minimal, Testable, Executable Example
Data
This example uses the (Strapi) URL http://localhost:1337/restaurants
, which returns the following array of JSON objects:
[{"id":1,"name":"Biscotte Restaurant","description":"Welcome to Biscotte restaurant! Restaurant Biscotte offers a cuisine based on fresh, quality products, often local, organic when possible, and always produced by passionate producers.","published_at":"2021-10-02T20:04:26.780Z","created_at":"2021-10-02T19:40:30.378Z","updated_at":"2021-10-02T20:04:26.816Z","categories":[{"id":2,"name":"Brunch","published_at":"2021-10-02T20:04:03.395Z","created_at":"2021-10-02T19:41:15.186Z","updated_at":"2021-10-02T20:04:03.437Z"}]}]
Sources
<script>
import axios from 'axios';
async function getRestaurants() {
return await axios.get('http://localhost:1337/restaurants');
}
let restaurants_promise = getRestaurants();
</script>
<main>
{#await restaurants_promise}
<p>wait...</p>
{:then restaurants}
<p>The restaurants are:</p>
{#each restaurants.data as restaurant}
<li>
{restaurant.name}
</li>
{/each}
{:catch error}
<p style="color: red">{error}</p>
{/await}
</main>
Notes
I don't want to use Strapi's tutorialonMount
and then/catch
blocks as I prefer to follow the Svelte's tutorial (see the Strapi's tutorial: the Strapi tutorial) ("Strapi" because in fact http://localhost:1337/restaurants
is a Strapi URL). I really try to stick to https://svelte.dev/tutorial/await-blocks.
Clues
With Postman, I can actually get the URL list of JSON objects so the network call works. So what is buggy is clearly my Svelte code.
With the Fetch API instead of Axios, my code works. I don't see anymore the error "TypeError: Cannot convert undefined or null to object".