Stas
Stas

Reputation: 695

React throws URIError: This is likely caused by an invalid percent-encoding

Was working in react and then encountered a problem like

  Uncaught URIError: This is likely caused by an invalid percent-encoding

Im working with news API at the moment and some of the articles might include %. My entire app depends on displaying news articles names in url because im using this.props.match.params.id

I tried to search for a solution online but most of them are very unclear when it comes to solving this exact problem.

Is there a simple workaround this issue?

Upvotes: 6

Views: 4572

Answers (3)

Because I use SSR using

 try {
    decodeURIComponent(req.path)
  } catch (error) {
    res.redirect(encodeURIComponent(req.path))
    return
  }

solved the issue

Upvotes: 0

Steven
Steven

Reputation: 1179

This did the trick for me.

     function navigate(data: Partial<Saturation>) {
    if (data.name) {
      const checkSyrupForPercentChar = data.name.includes('%')
      const syrupReplacementName = data.name.replace('%', '')

      history.push({
        pathname: `saturation-directory/${data.id}/${urlFormat(
          checkSyrupForPercentChar ? syrupReplacementName : data.name
        )}`,
        state: {
          syrupData: data,
          from: 'syrupDirectory'
        }
      })
    }
  }

The code before refactor:

      function navigate(data: Partial<Saturation>) {
if (data.name) {
  history.push({
    pathname: `saturation-directory/${data.id}/${urlFormat(data.name)}`,
    state: {
      syrupData: data,
      from: 'syrupDirectory'
    }
  })
}

}

The takeaway is the string functions that I incorporated as well are the ternary operator on the pathname.

Upvotes: 0

Andr&#233;s Hevia
Andr&#233;s Hevia

Reputation: 46

You need to use encodeURIComponent() with the path you receive as parameter: Example:

const receivedArticleName = encodeURIComponent('Article Name with %');

Since you are working with an API, once you receive it, set your URL variable with that receivedArticleName and you're done.

Upvotes: 3

Related Questions