how to pass json data from +layout.server.ts to +layout.svelte safely? #6652
-
|
I get json data from server and want to display on views. +layout.server.ts /** @type {import('./$types').LayoutServerLoad} */
export async function load() {
let menus = await get_menus();
console.log(typeof (menus))
console.log(menus);
return menus;
}
async function get_menus() {
let url = 'http://127.0.0.1:3333/api/menus';
const res = await fetch(url);
return await res.json();
}it give me in console. object
[
{ title: 'Dashboard', link: '/' },
{ title: 'Statics', link: '/statics' },
{ title: 'Support', link: '/supports' },
{ title: 'Login', link: '/auth/login' },
{ title: 'Settings', link: '/settings' }
]+layout.svelte <script lang="ts">
export let data: Object = {};
console.log( typeof(data))
console.log(data)
let menus = data;
</script>
// the menus will be passed to Menu ComponentBut in +layout.svelte , it gives me this in console. object
{
'0': { title: 'Dashboard', link: '/' },
'1': { title: 'Statics', link: '/statics' },
'2': { title: 'Support', link: '/supports' },
'3': { title: 'Login', link: '/auth/login' },
'4': { title: 'Settings', link: '/settings' }
}
why the Object data is being changed ? And how can I keep the original json data when passing to svelte ? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
|
You will need to always return data from a load function as an /** @type {import('./$types').LayoutServerLoad} */
export async function load() {
let menus = await get_menus();
console.log(typeof (menus))
console.log(menus);
- return menus;
+ return { menus };
}Now, Next, we can extract the You can also use generated types to get the autocomplete and suggestions for the returned object from load. <script lang="ts">
+ import type { PageData } from './$types';
- export let data: Object = {};
+ export let data: PageData;
console.log( typeof(data))
console.log(data)
- let menus = data;
+ $: ({menus} = data);
</script> |
Beta Was this translation helpful? Give feedback.
You will need to always return data from a load function as an
object. Currently,get_menus()is returning an array of objects./** @type {import('./$types').LayoutServerLoad} */ export async function load() { let menus = await get_menus(); console.log(typeof (menus)) console.log(menus); - return menus; + return { menus }; }Now,
loadis returning an object with themenuskey.Next, we can extract the
menuskey fromdata, declare, and set it all at once.You can also use generated types to get the autocomplete and suggestions for the returned object from load.