Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Import function from js file into svelte but variable is not defined

I would like to import a function from a js file into App.svelte. The function includes a variable c that is not defined in the js file. C changes values but I don’t want my function to be reactive to the change in c, only reactive to the change in b. When b changes my funcion should use whatever the value of c is. When I define the function in the app.svelte it works but not with the import.

How can I accomplish that?

Here is a repl:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

App.Svelte

<script>
    
    import {sum} from './function.js'
    
    let a = 1;
    let b = 2;
    let c = 3;
    let res;
    $: res = sum(a, b);
    
</script>

<button on:click={() => c=c+1}>
    C
</button>
<button on:click={() => b=b+1}>
    B
</button>
{res}
{c}
export function sum(a, b) {
    return a + b + c
}

>Solution :

You could curry it:

export const sum = c => (a, b) => a + b + c;
import { sum } from './function.js';

// ...
const c = 3;
const sumWithC = sum(c);
$: res = sumWithC(a, b);

(Extracting such a basic function probably does not make much sense, though.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading