2

I have a simple custom component in Svelte, where I use reactivity to execute some code.

<script lang="ts">
    export let liked: boolean
    $: {
         //..code that should be executed when liked is toggled ...//
    }
</script>

My problem is that when the component first mounts liked is toggled and the code is executed which is not what I want, I want to execute the code only when the user initiate the toggle.

That is why I added this initial variable here, which is making my code work as expected, but was wondering if there is a more idiomatic/clean way to do this?

<script lang="ts">
    export let liked: boolean
    let initial = true
    $: {
        if (!initial) {
            //..code that should be executed when liked is toggled ...//
        } else {
            initial = false
        }
    }
</script>
3
  • How is the liked flag set? Commented Apr 25, 2024 at 18:06
  • why not just use liked in a conditional block, given it is of boolean type? Commented Apr 25, 2024 at 18:08
  • liked is just a prop, that use bind:liked in the parent. If a user clicks on the like button then I do some transition on the component but I also trigger a popup for 2 seconds, which if I don't guard with the initial variable is triggered to all components when they mount. Commented Apr 25, 2024 at 18:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.