Skip to content
Advertisement

How can I get the access of a const inside my function?

How can I grant access to my const to be used inside a function? In this case I want to access my const catName inside my function fetchListings. I’m getting this error:

Question Updated:

JavaScript

JavaScript

Advertisement

Answer

The problem you are running into is coming from how the <script context="module"> works.

The module level script tag serves as a one-time-per-app setup script. That means it will run only one time, when your app is initialized and it will be run before any of the regular <script> tag code is run. See: https://svelte.dev/docs#component-format-script-context-module

This mean that the <script context="module"> won’t have any access to what’s defined or created in the normal <script> tags’ code. Thus the not defined error for your constant, which is defined in the regular <script> tag.

Based on this, your code would need to be refactored (reorganized). My understanding is that you put the fetchListings in the module context because you want to pre-fetch the results and only do it once during the startup of your app.

To accomplish that you can refactor your code like this:

JavaScript

This ensures that the fetchListings function only runs once. The trick is that variables, constants, etc defined in the module context are accessible to all instances of that model. So when the first instance is being created it will run the fetchListings function, and sets the preFetched variable to false, so the subsequent instances will no do that.

This is just one possible way to do it. Depending on what exactly you want to accomplish you might want to organize things differently. But with the understanding of what does the <script context="module"> do and when it runs, you should be able to come up with your own solution best suited for your needs.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement