Search code examples
salesforcesvelteapexlwc

console log a reactive prop in lwc


Hello I am learning salesforce and the documentation is sometimes vague for lwc. I am coming from svelte / react and I want to console log the value of a variable being passed down from parent to child. The syntax is not clear to me.

I think @api is basically like exposing a variable as a prop. But do I use @wire or getter to simply log changes to a variable?

    export let disabled; <--svelte
    @api disabled;<--salesforce


    $: console.log(disabled)<--svelte
    what is equivilent??? <--salesforce
 
What is the equivilent of doing $: console.log(this.disabled) from svelte to log reactive changes?
    

Solution

  • Never heard about svelte before but

    Try not exposing the real variable @api. Instead have a normal variable (there's convention of prefixing "privates" with an underscore but it doesn't have any power, doesn't change anything in access rules) and expose a getter/setter and then in setter you could inject any side effects you want?

    https://developer.salesforce.com/docs/platform/lwc/guide/js-props-getters-setters.html

    https://github.com/trailheadapps/lwc-recipes/blob/main/force-app/main/default/lwc/todoList/todoList.js

    There's even school of thought (eslint code smell rule) that says if you exposed something as @api you shouldn't modify it directly yourself. Don't treat it like an oracle but seems 1 more use case for getter / setter. https://github.com/salesforce/eslint-plugin-lwc/issues/91#issuecomment-1709204840