-1

I have this url http://localhost:3000/#/consultation/?idc=xxxd?iduser=Hyfzjg2 and I want to get the value of idc and iduser for using it on my APIs with ReactJs.

I try this:

let isInitialized = false;
const initialValues = {};
const initValues = () => {
    if (isInitialized === false) {
        const searchParams = new URLSearchParams(window.location.hash);
        const values = [
            { urlKey: "idc", stateKey: "idC" },
            { urlKey: "iduser", stateKey: "idUser" },
        ];
        values.forEach(item => {
            const urlValue = searchParams.get(item.urlKey)
            if (urlValue) {
                initialValues[item.stateKey] = urlValue;
            }
        });
        isInitialized = true;
    }
    return initialValues;
};

console.log(initValues())

When I run it, I get {} an empty value.

How can I get the value of idc and iduser ?

Ichrak Mansour
  • 1,850
  • 11
  • 34
  • 61

2 Answers2

1

I think you're path isn't constructed correctly:

If you have the path http://localhost:3000/consultation and you want to add a query string, that would be http://localhost:3000/consultation?idc=xxxx and window.location.search would be ?idc=xxxx then.

The # is a selector for an element on your page, for example #section=4, so you would typically scroll to that section. This would look like this:

http://localhost:3000/consultation#section=4 and window.location.hash would be "#section=4"

torquan
  • 356
  • 1
  • 6
  • _“I think you're path isn't constructed correctly”_ - this kind of URL structure is pretty common for “one page” applications, or systems that use client-side routing. Changing the _actual_ query string would force a reload of the current page; only changing the URL fragment portion does not do that. So a “fake” query string placed _inside_ the fragment is used in those kind of scenarios. – CBroe Apr 03 '20 at 09:43
  • Thank you @CBroe, didn't know that. Then your solution definitely makes sense, sorry @CodeLover! – torquan Apr 03 '20 at 09:56
0

I correct it and It works well :

const  getUrlParams = (search) =>{
  let hashes = search.slice(search.indexOf('?') + 1).split('&')
  return hashes.reduce((params, hash) => {
      let [key, val] = hash.split('=')
      return Object.assign(params, {[key]: decodeURIComponent(val)})
  }, {})
}

console.log(getUrlParams(window.location.hash))
Ichrak Mansour
  • 1,850
  • 11
  • 34
  • 61