0

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?

5
  • I suspect psTom should be an object {}, not an array []
    – Barmar
    Commented Apr 22 at 20:20
  • JSON.stringify() of an array will only return the indexed array elements, not named properties.
    – Barmar
    Commented Apr 22 at 20:21
  • I called it an array because the log always displays the contents inside [...], but yes it is an object {...}
    – k4mars
    Commented Apr 22 at 20:51
  • In JS you have to use {} syntax, let psTom = {};. I don't know Svelte.
    – Barmar
    Commented Apr 22 at 20:53
  • I changed let psTom = [] to let psTom = {} and didn't make any difference to the result, still works on server, empty on client. However, the code above was a cut down version I was using because my massively large code was too complex, itself containg both arrays and objects. By changing [...] to {...} for every object within my larger array it worked ! Thanks Barmar
    – k4mars
    Commented Apr 22 at 22:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.