I am trying to use the load() function in the +page.js file to fetch data, which works fine after the initial load of the page. Though if I refresh the page (or change the code and it auto-refreshes) it gives me an error: "500 Internal Error".
I can navigate to another route on my page and go back to this page and it works again.
+page.js:
export async function load() {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts');
    const books = await res.json();
    return {
        books
    }
}
+page.svelte:
<script>
    export let data
    let id = parseInt(new URLSearchParams(window.location.search).get('id')) - 1
</script>
<h2>{data.books[id].title}</h2>
<p>{data.books[id].body}</p>
What am I doing wrong?
You're calling window before initialization, this code is evaluated server-side, in a context where it does not exist.
Import browser helper utility from sveltekit to deal with this, like so:
import { browser } from '$app/environment';
export let data;
let id = 0;
             
if (browser)
  id = parseInt(new URLSearchParams(window.location.search).get('id')) - 1
                        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