Reputation: 125
I am using getContext with svelte-simple-modal for modals in my project.
Is there a way to use getContext etc. in Typescript files?
I am getting a 500: Function called outside component initialization
when calling svelte functions in Typescript files.
I have tried the methods mentioned in how-do-you-import-a-svelte-component-in-a-typescript-file.
Thanks for any help!
Upvotes: 5
Views: 3594
Reputation: 5426
You can use getContext
inside TypeScript files, but you can only call it during initialization of the component - that is, the first time the contents of the component's script tag are run.
// TS code
import { getContext } from 'svelte';
export function getFooContext() {
const foo = getContext('foo');
}
export function fails() {
setTimeout(() => getFooContext(), 100);
}
// Svelte code
<script>
import { getFooContext } from './somewhere';
// this is ok
getFooContext();
// this fails because it's called after the component is initialized
setTimeout(() => getFooContext(), 100);
// this fails because the function has a setTimout which is resolved
// after the component is initialized
fails();
</script>
You cannot call getContext
or setContext
or any of Svelte's lifecycle functions outside of the component initialization, which means you can't call it
Upvotes: 8