0

I am losing my mind, respectfully.

I am currently coding an assignment for my studies. I have to call an API using the async fetch method in Javascript using the Svelte framework. This is what i have in my app.svelte.

<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'>

<title>Sollicitatie Opdracht Volcano</title>

<link rel='icon' type='image/png' href='/favicon.png'>
<link rel='stylesheet' href='/global.css'>
<link rel='stylesheet' href='/build/bundle.css'>

<script defer src='/build/bundle.js'>
    import { onMount } from "svelte";

    const searchAnime = async () => {
        var response = await fetch('https://api.jikan.moe/v4/anime?q=jujutsu', {
            method: 'GET'
        });
        var result = await response.json();
        return result;
    }

    let aniSearchPromise = searchAnime();

</script>

<h1>API Fetching System</h1>


<main>  
{#await aniSearchPromise}
    <h2>Laden. . .</h2>
{:then data}
    <h2>{data.results[0]}</h2>
{:catch err}
    <h2>Error while loading data.</h2>
{/await}
</main>

<svelte:head>
    <title>aniAPI Test App</title>
</svelte:head>

<style>
    main {
        background-color: lavenderblush;
        font-size: 15px;
    }
    h1 {
        font-size: 25px;
    }
</style>

I am getting an error at

data.results[0]

I have no clue how to fix this as I can see that the promise is listed as fulfilled. On data.results[data[2]] is all the fetched data. See screenshot below Screenshot

Would anyone be able to explain what is happening and why it is undefined? Many thanks.

KylianJay
  • 55
  • 1
  • 8
  • Does this answer your question? [TypeError: Cannot read properties of undefined (reading 'id')](https://stackoverflow.com/questions/68959632/typeerror-cannot-read-properties-of-undefined-reading-id) – Hef Apr 03 '22 at 20:12
  • 1
    looks like there's no `results` in that object - you probably want `data[2]` instead of `data.results[2]` – tbjgolden Apr 03 '22 at 20:16

3 Answers3

3

data.Results is not an array and and by seeing your object, probably data.Results does not exist here. In your object, data is an array so it should be used like data[2].

1

It seems that data has no attribute called results in your screenshot. Can't you just call data[0] or data[2] ?

Dj0ulo
  • 440
  • 4
  • 9
0

Api works correctly, probably you are trying to get data before it fetches

var response = fetch('https://api.jikan.moe/v4/anime?q=jujutsu', {
  method: 'GET'
}).then(response => response.json())
.then(result => {
  console.log('Data [0] result', result.data[0]);
})
 
Evren
  • 4,147
  • 1
  • 9
  • 16