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

SvelteKit fetching on the server and updating the writable store

$
0
0

I was wondering what is the best way to do data fetching in SvelteKit since I ran into the following problem on my app.

I have a writable store like so:

import { writable } from "svelte/store";export const todosStore = writable();

As you see I have no initial value on my store. Then on the "+page.server.js" file I do my data fetching logic:

export async function load() {  // fetch the todos on the server  await getTodos();  return {};}
export const getTodos = async () => {  const todos = await db.collection("ToDo").find().toArray();  let serializedTodos = todos.map(({ _id, ...rest }) => {    return {      ...rest,      id: _id.toString(),    };  });  todosStore.update(() => serializedTodos);};

I then loop over the todos from the store and display a list of items. The problem is, on the first render on the browser I get the following error:

[HMR][Svelte] unrecoverable HMR error in <ToDoList>: next update will trigger a full reload
Uncaught (in promise) Error: {#each} only iterates over array-like objects.

It kinda makes sense, since the store has no initial value. I then decide to change the original value of my store to an empty array (since the fetched data come into an array), like so:

export const todosStore = writable([]);

When I make this change, the UI renders with the correct state (the todos store has the fetched data) and after a short time, the data disappear and I get an empty array.

Is this the expected behavior from SvelteKit? What is the correct way to do data fetching if I need to fetch on the server (I have API keys on the db call, so I can't fetch on the client since Vite throws me an error).


Viewing all articles
Browse latest Browse all 1541

Trending Articles



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