Svelte: initialize a variable after data load

Viewed 240

I am working on a recipe website. A recipe has a default servings number (eg: 4 people). The user can change the servings to dynamically update the recipe's proportions.

How can I do that in Svelte when my servings variable is fetched with @urql/svelte?

Once I receive the data in Svelte, my idea was to create a defaultServings variable based on the fetched servings value. defaultServings should not be updatable. I would then calculate a ratio for each ingredients such as ingredientQuantity / defaultServings * inputServings, servings. (here, servings is the fetched value that I'd bind to the input component.)

I'm new to Svelte and I think I over-complicate things. I don't know how to get the value of servings after query(getRecipe) is executed. query does not return a Promise, so I'm not sure how to await for the value to be fetched inside script.

<script>
    import { gql, operationStore, query } from '@urql/svelte'

    // Here, urql creates a writable store
    const getRecipe = operationStore(gql`...`)
    query(getRecipe)

    // How can I get the value of servings?
    const servings = getRecipe?.data?.servings
</script>
1 Answers

If you do const servings = ... it will always have the initial value which probably is undefined. If you want servings to be updated once the recipe is loaded and has data change it to be reactive:

$: servings = getRecipe?.data?.servings

This will effectively say "recalculate servings whenever what is on the right hand side changes"

Related