Search code examples
javascriptfetchsveltesveltekit

Sveltekit & Fetching data to use within HTML


I feel like i'm missing something obvious but I can't for the life of me figure out what it is i'm missing. I'm essentially trying to perform a fetch call in a call, and then use that data within the page. I can't get the data to actually work on the page though. It works if I console.log it within the tag, but once I try in the HTML I get undefined. Any idea what i'm doing wrong? Thanks for any help!

<script>
let gameinfo = async (chardata) => {
        chardata = toTitleCase(chardata);

        const gamedetails = await fetch('https://api.igdb.com/v4/games', {
            method: 'POST',
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Content-type': 'application/json'
            },
            body: `fields *;\nwhere name= "${chardata}";`
        })
            .then((res) => res.json())
            .then((gamedata) => {
                gamedata.map((e) => {
                    console.log(e);
                });
                return gamedata;
            })
            .catch((e) => {
                console.log(e);
            });
    };

    export let gameJson = gameinfo('Snatcher');
</script>

which returns a console logs of the mapped variable.

and the call in the html:

<main>
    <div class="mainContent">
        <div class="contentBlock">
                {console.log(gameJson)}
        </div>
    </div>
</main>

which returns undefined


Solution

  • First you didn’t return gamedetails.

    For gameinfo, it should be called in onMount‘s callback with await to get gameJson

    import { onMount } from 'svelte'
    
    let gameinfo = async (chardata) => {
      chardata = toTitleCase(chardata);
    
      const gamedetails = await fetch('https://api.igdb.com/v4/games', …)
    
      // you can verify it’s not undefined here
      console.log('check:', gamedetails)
      return gamedetails
    }
    
    export let gameJson
    
    onMount(async () => {
      gameJson = await gameinfo('Snatcher')
    })