How to fetch query parameters from url and use them inside a module

I’m trying to populate a module’s CTA href with the current url query params. The issue is that on the query params seem to be injected into the URL AFTER the component (module) is rendered on the page, so when I try to get them with window.location.search - it returns an empty string on the first search.

Is there any other way to fetch the query params - maybe some global app state, where they are stored?

I saw that the in the Yext Answers QA module something similar is already happening - the question’s textarea is being populated with the url query params:

Hi Petya,

I noticed the CTA you highlighted is part of the “full_width_promotion” component within your codebase. The component pulls variables from KG, specifically from your c_heroSection cf. Within your dataForRender(profile) func, I went ahead and did a function call to ANSWERS.core.storage which is a map that contains the state of your answers experience, and thus keeps track of the URL Query Params among other variables (like language). The official github repository for answers-storage is https://github.com/yext/answers-storage/ and the particular service we’ll be leveraging is defined here https://github.com/yext/answers-storage/blob/main/src/index.ts

Please use the code below to pull the query params “before” you render the buttons onto the page, then pull the query parameter in question, and “mutate” the link for your CTA before passing it to the template that takes care of rendering the HTML. Since I’m not familiar with the code base, and I saw in your question that you wanted to scope the change to only the button that had the “search” text within, I went ahead and only applied the tweak to that button by having the code look for the cta label = “search”

Here’s a snippet of code that should take care of pulling the query parameter and “setting it” on the link provided by the cf.

        // pick the item that we want to add query params to
        if (label.toLowerCase() === 'search') {
          const ctaLink = new URL(link);
          const query = ANSWERS.core.storage.get('query');
          if(query) {
            ctaLink.searchParams.set('query', query);
          }
          link = ctaLink.toString();
        }

I’ve gone ahead and applied the code changes above to the branch hh-support. Would you mind testing them and letting us know if this solves your issue?

Thanks,
Mau

Hi Mau,

ANSWERS.core.storage was exactly what I was looking for!

And yes, I can confirm that your code solves the issue! :tada:

It’s pretty much what I had already, but I was trying to get the query with:
new URLSearchParams(window.location.search).get("query").

Thank you very much for your help!