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
It looks like your issue is the fact that you are returning the function
onSnapshot()
inside theload
function. The only thing you can return inside aload
method is a plain object as the error states. What you might want to do is to run the snapshot code inside anonMount
.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
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 usingfetch()
, 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 inonMount()
, so you only subscribe to future updates when the component is rendered in the web browser.