Steps to resolve the "fetch failed" issue in Svelte

I currently have 2 files saved locally

The code within the +page.svelte file is shown below:

<script lang="ts">
import type { PageData } from "./$types";
import { generations } from "./generations";

export let data: PageData;

</script>

{#each  data.monsters as monster (monster.url)}
    <h1>{monster.id}: {monster.name}</h1>
{/each}

{

#each  generations as generation (generation.id)}
    <h1>{generation.name}</h1>
    <p>Games: {generation.games.join(', ')}</p>
    <p>Main Region: {generation.main_region}</p>
{/each}

The code within the +page.ts file is shown below:

    import type { PageLoad } from './$types'
type IndexMonster = {
    name: string
    url: string
}

export const load  = (async ({ fetch }) => {
    const response   = await fetch('https://pokeapi.co/api/v2/pokemon?limit=20')
    const json       = await response.json()
    const monsters   = json.results.map((monster: IndexMonster) => {
        const splitUrl  = monster.url.split('/')
        const id        = splitUrl[splitUrl.length - 2]
        return {
            name: monster.name,
            url: monster.url,
            id,
        }
    })
    return {
        monsters: json.results
    }
}) satisfies PageLoad

An error message I encountered is displayed below:

TypeError: fetch failed

at fetch (D:\Documents\Ty\THE BIM FACTORY 4.7.2022\Code\WepApp\- js-pokedex-sveltekit\node_modules\undici\index.js:109:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.eval [as fetch] (/node_modules/@sveltejs/kit/src/runtime/server/fetch.js:27:10)
at async eval (/node_modules/@sveltejs/kit/src/runtime/server/page/load_data.js:195:18)
at async load (D:/Documents/Ty/THE BIM FACTORY 4.7.2022/Code/WepApp/- js-pokedex-sveltekit/src/routes/+page.ts:9:23)

If you could offer any assistance in resolving this error, it would be greatly appreciated as I am relatively new to Svelte!

The desired outcome upon resolution can be viewed in the following link: enter image description here

Answer №1

Ensure that the API endpoint URL you are attempting to reach is accurate and the API functions correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The 'searchText' property is missing an initializer and is not definitively assigned within the constructor

There is a variable declared in a class: public searchText: string; With strict mode enabled in TypeScript, the following error occurs: Property 'searchText' has no initializer and is not definitely assigned in the constructor Adding '&a ...

How to Utilize an Array from Observable Object in Angular 2 with ngFor and Async Pipe

I am currently learning about the utilization of Observables in Angular 2. Here is a snippet of code from a service I am working with: import {Injectable, EventEmitter, ViewChild} from '@angular/core'; import {Observable} from "rxjs/Observab ...

Customize back button functionality in Ionic 2

Is it possible to modify the behavior of the back button shown in this image? I would like to specify a custom destination or perform an action before navigating back, instead of simply returning to the previous page. https://i.stack.imgur.com/EI2Xi.png ...

The React Fabric TextField feature switches to a read-only mode once the value property is included

I've been grappling with how to manage value changes in React Fabric TextFields. Each time I set the value property, the component goes into read-only mode. When utilizing the defaultValue property, everything functions correctly, but I require this i ...

Anticipating the completion of multiple observable subscription functions

Is there a way to replace and convert all words in an array using an object's method that returns an observable? I found a helpful solution on this post which uses bind to pass the correct value. After all subscriptions are complete, I want to execut ...

Creating a button that emerges from another button

Currently utilizing Angular 5, I am looking to add an additional button that will display upon clicking another button. I am considering using the ngIf directive, but I am uncertain about how to target the specific button that was clicked. Here is an exc ...

What does this.userSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('user'))); signify?

I'm attempting to deconstruct this specific code snippet to comprehend it better. The new BehaviourSubject appears to be a function call, but I'm confused about what it's doing there. Is it instructing the function BehaviourSubject to have a ...

Show the attribute of an element in a pop-up window

I have a modal from ngx-bootstrap that I want to display in there a property of my object let's say the name: public students = [ { id: 1, name: 'lorem'} In this button that is common for all entries in the table (each row has this butt ...

I am having trouble getting debugging with source maps to work in VSCode and Browserify

I'm currently experiencing an issue with setting breakpoints in Chrome using VSCode, especially when working with TypeScript and Browserify. Oddly enough, if I open Chrome separately and manually refresh the page, the source maps load correctly and I ...

typescript in conjunction with nested destructuring

ES6 has definitely made coding more efficient by reducing the number of lines, but relying solely on typescript for everything may not be the best approach. If I were to implement type checking for arguments that have been destructed multiple levels deep, ...

Troubleshooting a Missing Call Display Issue in Angular2 API

Greetings, I am a new web developer and I have been tasked with creating a prototype Inventory Page using Angular2. Please bear with me as my code may not be perfect. In the snippet below, you'll notice that we are calling our base back-end API (&apo ...

In TypeScript, what do we call a property that is accessed dynamically?

I have a reusable function that can be used on various properties of a custom type. Here's an example: interface MyType { prop1: string; prop2: number; } type MyTypeKey = keyof MyType; const testValue = ( obj: MyType, property: MyTypeKey, v ...

Displaying continuous hours on the X-Axis within a 24-hour time series using Recharts

I've been attempting to showcase server data on a scatter chart with multiple y axes, but I'm encountering issues with duplicate hours on the X axis: https://i.sstatic.net/Spd7u.png Here's the code snippet I have so far: <XAxis dataK ...

This component is not compatible with JSX syntax and cannot be used as a JSX component. The type '() => Element' is not suitable for JSX element rendering

My Nextjs seems to be malfunctioning as I encountered the following error in a Parent component. Interestingly, the Spinner Component remains error-free Spinner.tsx export default function Spinner() { return ( <div className='flex ...

`The form input status color remains static and does not update`

I encountered a situation in one of my projects where I need to visually indicate if a field is correct or incorrect based on the value of another field. To better illustrate this issue, I have created an example here. The main challenge: I am struggling ...

Legend in AMCharts 5 remains visible even after deleting the chart

I integrated an AMCharts 5 chart into my Angular application that requires removal upon a specific action. However, even after deleting the chart, the legend tooltips continue to be displayed. Below is the code snippet used to generate the chart : this ...

Ways to establish cache in a server-side next.js environment

Having issues with 'node-cache' implementation in my Next.js backend. Below is the code for my cache file: cache.ts import NodeCache from 'node-cache'; const Cache = new NodeCache({ stdTTL: 60 * 60 * 6 }); // 6 hours export default Cac ...

`Why does the npm test command in vue2 source code fail with the error "Type ... is not assignable to type ..."?`

After cloning the Vue source code from github using git clone, I proceeded to install dependencies by running yarn. However, when I ran npm test, the test failed. https://i.sstatic.net/aZXBg.png Does anyone have insight on why this error occurred and how ...

The function Sync in the cp method of fs.default is not a valid function

When attempting to install TurboRepo, I encountered an issue after selecting npm. >>> TURBOREPO >>> Welcome to Turborepo! Let's get you set up with a new codebase. ? Where would you like to create your turborepo? ./my-turborepo ...

Managing Concurrent Actions in Redux: Strategies for Handling Multiple Actions of the Same Type Simultaneously

In my current project, I have implemented a feature where each row in a list of songs has a like button. When the like button is clicked, it triggers a LIKE_SONG action, which then initiates an asynchronous API request. Depending on the response, we can re ...