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 belowWould anyone be able to explain what is happening and why it is undefined? Many thanks.
CodePudding user response:
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]
.
CodePudding user response:
It seems that data has no attribute called results
in your screenshot. Can't you just call data[0]
or data[2]
?
CodePudding user response:
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]);
})