'How do I display value(s) of fetch function?
I'm struggling to extract certain data values and put them in my website. I'm getting data from an API in JSON format. This is then handled by the handleResponse function. Now I wish to display one or more of these received values on my website. Any clues on how to properly do this? I've tried just about everything to the best of my ability. I am also aware that {dataList} is currently not a used variable. This is just to state where i want my data to be. Thanks.
<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";
// Here we define our query as a multi-line string
// Storing it in a separate .graphql/.gql file is also possible
var query = `
query ($id: Int) { # Define which variables will be used in the query (id)
Media (id: $id, type: ANIME) { # Insert our variables into the query arguments (id) (type: ANIME is hard-coded in the query)
id
title {
romaji
english
native
}
}
}
`;
var dataList;
// Define our query variables and values that will be used in the query request
var variables = {
id: 15125
};
// Define the config we'll need for our Api request
var url = 'https://graphql.anilist.co',
options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query: query,
variables: variables
})
};
// Make the HTTP Api request
fetch(url, options).then(handleResponse)
.then(handleData)
.catch(handleError);
function handleResponse(response) {
return response.json().then(function (json) {
return response.ok ? json : Promise.reject(json);
});
}
function handleData(data) {
console.log(data);
}
function handleError(error) {
alert('Error, check console');
console.error(error);
}
</script>
<h1>API Fetching System</h1>
<main>
<h2>{dataList}</h2>
</main>
<svelte:head>
<title>aniAPI Test App</title>
</svelte:head>
<style>
main {
background-color: lavenderblush;
font-size: 15px;
}
h1 {
font-size: 25px;
}
</style>
Solution 1:[1]
I fixed the issue.
By declaring a var dataString = ''; in the beginning, and in the HandleData function, I stringify the data using dataString = JSON.stringify(data);
then down below where dataList used to be:
{#await dataString}
{:then dataString}
<h2>{dataString}</h2>
{/await}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KylianJay |

