Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Fetch data using Prisma in Sveltekit

$
0
0

I'm learning Sveltekit and trying to figure out how to fetch data from my postgresql database via Prisma (prisma.casino.findMany()). I'm aware I might be quite far off in my code and would appreciate some help on the way.

Right now I am just receiving an:

Cannot read properties of undefined (reading 'length')on the: "{#each casinos as casino (casino.id)}" line in the index.svelte file.

How do I correctly fetch data in Sveltekit using prisma?

Please see my files below:

components/Casino/_api

import type { Locals } from '$lib/types';import PrismaClient from '$lib/prisma';import type { RequestEvent } from '@sveltejs/kit';import type internal from 'stream';const prisma = new PrismaClient();export type Casino = {    id: string;    name: string;};export async function api(event: RequestEvent, resource: string, data?: Casino) {    let body = {};    let status = 500;    switch (event.request.method.toUpperCase()) {        case 'GET':            body = await prisma.casino.findMany();            status = 200;            break;    }    if (        event.request.method !== 'GET'&&        event.request.headers.get('accept') !== 'application/json'    ) {        return {            status: 303,            headers: {                location: '/'            }        };    }    return {        status,        body    };}

components/Casino/index.json.ts

import type { RequestHandler } from '@sveltejs/kit';import { api } from './_api';// GET /todos.jsonexport const get: RequestHandler = async (request) => {    // request.locals.userid comes from src/hooks.js    const response = await api(request, `casinos/`);    if (response.status === 404) {        // user hasn't created a todo list.        // start with an empty array        return { body: [] };    }    return response;};

components/Casino/index.svelte

<script context="module" lang="ts">    import type { Load } from '@sveltejs/kit';    // see https://kit.svelte.dev/docs#loading    export const load: Load = async ({ fetch }) => {        const res = await fetch('/casinos');        if (res.ok) {            const casinos = await res.json();            return {                props: { casinos }            };        }        const { message } = await res.json();        return {            error: new Error(message)        };        console.log(res);    };</script><script lang="ts">    import type { Casino } from './_api';    export let casinos: Casino[];</script><section>    {#each casinos as casino (casino.id)}<p>{ casino.name } </p>    {/each}</section>

Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>