Home > Software design >  Svelte can't seem to write data to variable after fetching from API
Svelte can't seem to write data to variable after fetching from API

Time:10-29

I've made myself an API which returns the following values:

[{"id":1,"title":"Illmatic","artist":"Nas","songs":["The Genesis","N.Y. State Of Mind","The World Is Yours"],"offer":25.01,"offer_owner":123456,"due_date":1669593600000,"genre":"hiphop","auction_owner":696969}, 
{"id":2,"title":"Life After Death","artist":"The Notorious B.I.G.","songs":["Intro","Things Done Changed","Gimme The Loot"],"offer":25,"offer_owner":696969,"due_date":1669593600000,"genre":"hiphop","auction_owner":123456},
{"id":3,"title":"After Hours","artist":"The Weekend","songs":["Alone Again","After Hours","Save Your Tears","Escape From LA","Snowchild"],"offer":25,"offer_owner":123456,"due_date":1369593600000,"genre":"pop","auction_owner":696969}]

I have the following Svelte code:

import { onMount } from "svelte";

let albums;

onMount(async () => { 
fetch("http://localhost:8080/api/albums/").then((response) => response.json().then( 
(data) => albums = data 
// console.log(data) returns data )); 
});

console.log(albums); // returns undefined?

Note: when I fetch the data from the API I get the data in my data variable. When I console log on it, it returns an array with 3 rows.

But when I want to write my data value to the albums variable it gets undefined when I call the console.log at the last row of the script. What am I doing wrong? I'm kinda stuck because I really don't know where the problem is.

See description of the problem

CodePudding user response:

Fetch is async so console.log(albums); executes before you get the response from your api.

CodePudding user response:

You have syntax errors in your promise code. Also, the console.log() statement is executed before the response from your API comes back from the server. Maybe it's advisable for you to learn more about asynchronous code because it can be tricky to understand.

In principle, your code looks similar to the example about onmount. So using it for reference might help you: https://svelte.dev/tutorial/onmount

You can debug by rendering your variable into the DOM/HMTL. Because the contents of objects are not directly converted to readable strings you can use JSON.stringify() for debugging. Also, check out the network tab for debugging API requests and responses.

    <script>
    import { onMount } from 'svelte';

    let albums = [];

    onMount(async () => { 
        fetch("/tutorial/api/album")
            .then((response) => response.json())
            .then((data) => {
                albums = data
            })
        // console.log(data) returns data )); 
    });
    
    </script>

    <h1>{JSON.stringify(albums)}}</h1>
  • Related