Load Data in page load functions
Works both server and client side.
Load Collection
Place this code in your corresponding +page.ts
file:
ts
import { getCollection } from 'sveltefirets';import { limit, orderBy } from 'firebase/firestore';import type { Message } from '$lib/message.interface';import type { PageLoad } from './$types';export const load: PageLoad = async () => {const messages = await getCollection<Message>(`messages`, [limit(5),orderBy('updatedAt', 'desc'),]);return { messages };}
Then in your +page.svelte
file:
svelte
<script lang="ts">import type { PageData } from './$types';export let data: PageData;$: ({messages} = data);</script>
If you want real-time updates, check out the collectionStore
function or check out the experimental incrementalCollectionStore
demoed below.
Refresh to see the flash of objects rearranging as the client side Firestore fetched, updated the content (and also cached).
Load Document
Works the same way except you import getDocument
in your +page.ts
file:
ts
import { getDocument } from 'sveltefirets';import type { Message } from '$lib/message.interface';import type { PageLoad } from './$types';export const load: PageLoad = async () => {const message = await getDocument<Message>(`messages/fooId`);return { message };}
The Message
type is optional in both instances but highly recommended as it will give you proper types for your returned data. If you want real-time updates, check out the docStore
and awaitableDocStore
functions.
Test out page loaded data for the above messages using the following links: