I am using Svelte5. When I send an array from +page.server.js to +page.svelte it always works server-side and the array is sent as expected. However when +page.svelte is running on the client side the array is always empty. Rather than ask a specific 'what's wrong with my code' I want to ask a general question - how do you send an array back to +page.svelte.
My cut-down code is -
// +page.server.js
export async function load({ url, cookies }) {
return { Tom: await setUpTom() }
}
async function setUpTom() {
let psTom = [];
psTom.NoOfRecords = 34;
psTom["L"] = [];
psTom["L"].NoOfRecords = 4;
return psTom;
}
// +page.svelte
...
let pcTom = data.Tom;
...
Below are my server-side logs (ps denotes action from +page.server, +p denotes action from +page.svelte) -
ps
psTom => [
NoOfRecords: 34,
L: [ NoOfRecords: 4 ],
A: [ F: [ Records: [Array] ] ]
]
+p
pcTom => [
NoOfRecords: 34,
L: [ NoOfRecords: 4 ],
A: [ F: [ Records: [Array] ] ]
]
They are the same. But this is the server-side log, so when +page.svelte runs server-side it works fine.
When running client-side the client log has pcTom as empty -
+p
pcTom =>
Array []
length: 0
I have tried lots of combinations of sending my array back (including using JSON below) and in each case it works fine server-side (psTom and pcTom are correctly populated arrays) but when +page.svelte is running client-side the array is empty (pcTom = []).
async function setUpTom() {
...
return JSON.stringify(psTom);
}
then let pcTom = JSON.parse(data.Tom);
What am I missing?
psTom
should be an object{}
, not an array[]
JSON.stringify()
of an array will only return the indexed array elements, not named properties.{}
syntax,let psTom = {};
. I don't know Svelte.