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:

ReferenceError: catName is not defined

<script context="module">

const fetchListings = async () => {

        try {
            // get reference to listings collection
            const listingsRef = collection(db, 'listings');
            // create a query to get all listings
            const q = query(
                listingsRef,
                where('type', '==', catName),
                orderBy(timestamp, 'desc'),
                limit(10)
            );
            // execute query
            const querySnap = await getDocs(q);

            let lists = [];

            querySnap.forEach((doc) => {
                console.log(doc);
            });

        } catch (error) {
            console.log(error);
        }
    };
    fetchListings();
</script>

<script>
    import { page } from '$app/stores';
    // export the const catName to the function above
    export const catName = $page.params.catName;
</script>

Hi {catName}!

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:

<script context="module">
  let preFetched=false
</script>

<script>
  import { page } from '$app/stores';

  // export is not needed
  const catName = $page.params.catName;  

  async function fetchListings() => {
    // Your code  ...
  } 
  if(!preFetched){
    fetchListings()
    preFetched=true
  }

</script>

Hi {catName }!

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