Search code examples
fetchsveltereloadsveltekit

Update Component after post new item to the Database


I am playing around with Sveltekit and I am struggling a bit..

So my problem is, when I add something to the DB it works, but the new Item does not show in the list until i Refresh the page. My Code looks like:

index.js

import { connectToDatabase } from '$lib/db';

export const post = async ({ request}) => {

    const body = await request.json()
    console.log(body)

    const dbConnection = await connectToDatabase();
    const db = dbConnection.db;
    const einkaufszettel = db.collection('Einkaufszettel')

    await einkaufszettel.insertOne({
        name: body.newArticle
    });

    const einkaufsliste = await einkaufszettel.find().toArray();

    return {
        status: 200,
        body: {
            einkaufsliste
        }
    };

}


export const get = async () => {

    const dbConnection = await connectToDatabase();
    const db = dbConnection.db;
    const einkaufszettel = db.collection('Einkaufszettel')
    
    const einkaufsliste = await einkaufszettel.find().toArray();

    console.log(einkaufsliste)

    return {
        status: 200,
        body: {
            einkaufsliste,
        }
    };

}

and the Script of index.svelte

<script>
    import Title from '$lib/title.svelte'
    export let einkaufsliste = []
    let newArticle = ''

    const addArticle = async () => {

        const res = await fetch('/', {
            method: 'POST',
            body: JSON.stringify({
                newArticle
            }),
            headers: {
                'Content-Type': 'application/json'
            }
        })

        fetchArticles()
    }

    async function fetchArticles() {
        const res = await fetch('/')
        console.log(res.body)
    }

</script>

In the Network Preview Tab the new Item is already added to the List.


Solution

  • As you can read here, you need to reassign the einkaufsliste after fetching the list of elements from the API.

    You can do this in your fetchArticles method, like this:

    async function fetchArticles() {
      einkaufsliste = await fetch('/')
    }