Search code examples
sveltesveltekit

How do I set a variable to props sent in sveltekit?


I am trying to set some values based on props passed in my sveltkit page to the component. The problem is when the component mounts the value is empty. What is the proper way to set a value from a prop sent? Below the prop sent is testPlate, which is an object. There is a value testPlate.plateLength. But when I set testVar = testPlate.plateLength I get the error TypeError: Cannot read properties of undefined (reading 'plateLength'). Maybe I need to send the value different, but this should work.

<script>
// @ts-nocheck

    export let testPlate;
    import * as Threlte from '@threlte/core';
    import * as Three from 'three';
    import * as Utils from 'three/src/math/MathUtils';
    import { onMount } from 'svelte';

    let testVar = testPlate.plateLength
    console.log(testVar)
    

</script>

I have a workaround using setTimeout in the onMount but that doesn't seem like how this is supposed to work.

<script>
    // @ts-nocheck

    export let testPlate;
    import * as Threlte from '@threlte/core';
    import * as Three from 'three';
    import * as Utils from 'three/src/math/MathUtils';
    import { onMount } from 'svelte';

    let testVar;
    console.log(testVar);
    onMount(() => {
        setTimeout(() => {
            testVar = testPlate.plateLength;
        }, 1000);
    });
    
</script>

Solution

  • It seems like you are mounting this component before testPlate is initialized, the ideal way would be to only mount it once this variable declared. So in your parent component you would have something like this:

    {#if testPlate}
      <Component {testPlate} />
    {/if}
    

    This way it will never be undefined.

    Aside from that you can also use reactivity to re-assign testVar once the other variable becomes defined:

    export let testPlate;
    $: testVar = testPlate?.plateLength;
    

    Be aware that you will have to handle in your markup the case where testVar is also undefined.