skip to Main Content

I cannot get SvelteKit load function works when using it with Firebase, I always get this error message:

a load function related to route ‘/’ returned a function, but must return a plain object at the top level (i.e. return {...})

I’m using onSnapshot here with Firestone to get the updated data whenever it changed on the database.

export function load() {  
    const queryParams = [orderBy('date')];
    const q = query(collection(db, 'daily_status'), ...queryParams);
    
    messagesUnsubscribeCallback = onSnapshot(
        q,
        querySnapshot => {
            let data = querySnapshot.docs.map( doc => (
                JSON.parse(JSON.stringify(
                    {
                        id: doc.id, 
                        status: doc.data().status, 
                        date: doc.data().date.toDate().toLocaleDateString('en-au'),
                        note: doc.data().note
                    } 
                ))
            ))
        return { daily_status: data }
    })
    return messagesUnsubscribeCallback;
}

2

Answers


  1. It looks like your issue is the fact that you are returning the function onSnapshot() inside the load function. The only thing you can return inside a load method is a plain object as the error states. What you might want to do is to run the snapshot code inside an onMount.

    Another solution would be creating a svelte store and pass the onSnapshot into the store. An example can be seen in this tutorial:
    https://www.captaincodeman.com/lazy-loading-and-querying-firestore-with-sveltekit#introduction

    Reference:
    https://kit.svelte.dev/docs/load

    Login or Signup to reply.
  2. Your load() function needs to run asynchronous code, so it can’t return back the data directly. Instead, you need to change it to return a promise that resolves to the loaded data. For an example using fetch(), see:

    https://kit.svelte.dev/docs/load#making-fetch-requests

    In your case, you need to create your own promise.

    Further more, the purpose of the load() function is to load the initial data the page needs to be able to render. As suggested by another, to subscribe to updates in the future, do that in the page component in onMount(), so you only subscribe to future updates when the component is rendered in the web browser.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search