thousight
thousight

Reputation: 1154

decodeURIComponent is not a function

I am trying to use this function in componentWillMount() of my React.js component. But the browser is saying window.decodeURIComponent(...) is not a function, which I don't understand. Can anyone tell me how to get it work? Thanks

export const getUrlQuery = window => {
  let queryDict = {}
  if (window.location.search) {
    window.location.search.substr(1).split("&").forEach((item) => {
      let s = item.split("=")
      let key = s[0]
      let value = s[1] && window.decodeURIComponent(s[1])
      (queryDict[key] = queryDict[key] || []).push(value)
    })
  }
  return queryDict
}

Upvotes: 2

Views: 2018

Answers (2)

Oblosys
Oblosys

Reputation: 15106

Interesting error, it turns out that the let value = .. line is parsed as

let value = s[1] && window.decodeURIComponent(s[1])(queryDict[key] = queryDict[key] || []) ..

In other words, you're applying the parenthesized expression to the result of window.decodeURIComponent(s[1]), which is string and not a function. You can fix it with an explicit semicolon (which is not a bad idea in general):

let value = s[1] && window.decodeURIComponent(s[1]);

UPD: Seeing what the code is doing, you might be interested in the qs npm package.

Upvotes: 5

thousight
thousight

Reputation: 1154

After I removed this part of the code, things work.

(queryDict[key] = queryDict[key] || [])

Looks like this grammar error is causing the yelling instead of decodeURIComponent()

Upvotes: 0

Related Questions