how to get only data from fetch

Viewed 47

I try to get only the data of my fetch request but when i go out of my function there is a promise arround.

I try to fetch an API for starting a store in svelteJS but I'm wrong.


import {writable} from "svelte/store";

const getPokedex = async function () {
    let pokedexData
    await fetch('https://pokeapi.co/api/v2/pokemon?limit=100&offset=0')
        .then(response => response.json())
        .then(data => {
            pokedexData = createPokedex(data)
        })
    return pokedexData
}

const createPokedex = function (data) {
    let pokedex = writable(data)
    ...
}

export const pokedex = getPokedex();


SOLVED:


const getPokedex = async () => {
    const response = await fetch('https://pokeapi.co/api/v2/pokemon?limit=100&offset=0');
    const data = await response.json();
    let pokedex = data.results
    return createPokedex(pokedex);
}
export const pokedexStore = await getPokedex();
1 Answers

Make use of async/await and try to not use then/catch while using async/await this will make your code more clean, readable, easy to work with

const getPokedex = async function () {
  const response = await fetch("https://pokeapi.co/api/v2/pokemon?limit=100&offset=0");
  const data = await response.json();
  return createPokedex(data);
};

this code will return the data you just have to wait for the promise using await

const pokedex = await getPokedex();

Related