Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async Axios call not executed in Svelte: trying to use the result raises a TypeError: Cannot convert undefined or null to object ; Fetch API working

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".

like image 970
JarsOfJam-Scheduler Avatar asked Oct 02 '21 21:10

JarsOfJam-Scheduler


People also ask

How do I use the async/await syntax in Axios?

In a new file getRequestAsyncAwait.js, add the following code: To use the async/await syntax, we need to wrap the axios.get () function call within an async function. We encase the method call with a try...catch block so that we can capture any errors, similar to the catch () method we used in the Promise version.

Why use svelte for asynchronous data?

Most web applications have to deal with asynchronous data at some point. Svelte makes it easy to await the value of promises directly in your markup: Only the most recent promise is considered, meaning you don't need to worry about race conditions.

Why can't I get the key from undefined in Axios?

Due to unfinished request, req doesn't get data from server. Therefore, its value is undefined. We can't get keys from undefined, hence the error. It is time to implement Axios with retry capability. But before going any further, I want to make clear when referring to retry, mostly we want to have control over two things:

Why can’t I use callbacks with Axios?

As Axios uses Promises to make network requests, callbacks are not an option when using this library. We interact with Axios using Promises, or the async/await keywords which are an alternative syntax for using Promises. If you are using CommonJS, there are two methods in Node.js to import the library.


1 Answers

There seems to be an error in the code that merges the user's config with the defaultConfig of axios (somehow the defaultConfig is undefined).

This issue was introduced in v0.21.2 so downgrading to latest v0.21.1 should work for the time being.

like image 111
Stephane Vanraes Avatar answered Oct 22 '22 11:10

Stephane Vanraes