I'm new to Sveltekit and I'm trying to share data among different routes. I know the stores are stored in memory and disappear when we change routes, that's why I'm using localStorage to persist data among routes.
src/stores/stores.js
import { writable } from 'svelte/store';
const storedUsers = JSON.parse(window.localStorage.getItem('users')) || [];
export const users = writable(storedUsers);
users.subscribe((value) => window.localStorage.setItem('users', JSON.stringify(value)));
When my application starts I'm able to update my store on the src/routes/+page.svelte default route by doing something like that:
src/routes/+page.svelte
<script>
import { users } from './stores/stores.js';
function addUser() {
users.update(list => [...list, `user-${list.length}`]);
}
</script>
<button on:click={addUser}>Add User</button>
However, when I try to retrieve this list from another route (using +page.js) I'm receiving ReferenceError: window is not defined. I know this code is running on Browser, then why window is not defined? And how can I retrieve the localStorage data?
src/routes/mylist/+page.js
import { browser } from '$app/environment';
export async function load() {
const myList = await JSON.parse(window.localStorage.getItem('mylist'));
console.log({ browser, myList }); // browser is true
}
Load functions from +page.js actually run both on the client and on the server. That's why you're getting that error.
The simplest solution is not to use localStorage at all. I think what would be the best idea for your case is to use sveltekit hooks, together with the locals parameter.
The scaffolding would look like this:
import type { Handle } from '@sveltejs/kit';
export const handle = (async ({ event, resolve }) => {
event.locals.user = /* your things */;
return await resolve(event);
}) satisfies Handle;
If you want to keep using localStorage, I think you would just need to check if you're in the browser on the load function (best way is to use the browser const that sveltekit exports), or do the data "fetching" in +page.js, using the onMount callback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With