Blog > How to pass data between layouts components in SvelteKit SSR
How to pass data between layouts components in SvelteKit SSR
SvelteKit Information technologySvelteKit is an amazing framework. Right now I'm working on a big project and I can confirm the quality of this excellent instrument. As I needed to use SvelteKit's SSR's potential significantly, I found myself facing problems that required a few minutes of research. One of these concerns the possibility of passing fetched data to the sub-components and views of any route.
For instance, let's say you have to load a list of names that must be shared by all or some components that will be rendered subsequently. This can be achieved through the "context" object exposed by the "load" function in a the script with context="module".
<script context="module"> export async function load({ context }) { const namesList = ["Alexander", "Cesar", "Cyrus"]; return { context: { namesList } } }
Note, the context object must be returned by the load function in order to be accessible by the components that will be initialized later on.
From now on, the namesList object can be reached by a child-component and made available to the page via the "props" property.
<script context="module"> export async function load({ context }) { const sharedNamesList = context.namesList; return { props { sharedNamesList } } }
Then subsequently used, again during the SSR phase. Here first remember to export the variable in the regular script.
<script> export let sharedNamesList; </script> <h1>{ sharedNamesList[0] }</h1>