microlinkhq / open

4 stars 2 forks source link

Invalid URL trying to resolve an URL #11

Closed DevoKit closed 5 years ago

DevoKit commented 5 years ago

I am trying to render a link preview with Microlink for a user inputed link in a react application. If the URL is incorrect, the entire app crashes with the error: Uncaught TypeError: Failed to construct 'URL': Invalid URL at getHostname (CardContent.js:39) at ./node_modules/react-microlink/lib/components/Card/CardContent.js.exports.default (CardContent.js:89)

Is there a way I can detect if the URL will crash the Microlink component ahead of time or another fix for this. Thank you

Kikobeats commented 5 years ago

Hello, @DevoKit

Just be ensure to pass a valid URL something like this should be enough:

const isValidUrl = url => {
  try {
   new URL(url)
   return true
  } catch(err) {
   return false
  }
}

Then use the helper before calling Microlink component:


{isValidUrl(url) && <Microlink url={url} />}

PS: SDK has is own repository: https://github.com/microlinkhq/sdk

DevoKit commented 5 years ago

Thank you for the reply @Kikobeats . I already have logic in place to catch if the URL is formatted correctly similarly to what you have above. the problem is a URL like https://dfgdfgdfgdfgdfakaskdhsd.com would return true but still crash the Microlink component and thus the app. Is there a way for me to test if the URL would crash the Component?

Kikobeats commented 5 years ago

Hmm currently the SDK doesn't have defined a specific state under this situation, I think it will be loading all the time, can you confirm?

What do you expect that happens under this scenario?

DevoKit commented 5 years ago

The user enters any URL they want and I have an onChange function on the input that checks if the URL is formatted correctly. If yes it sends the URL to the Microlink component to generate the link preview. if the user enters a non existing URL that is formatted correctly the Microlink component and the app crashes. I think I need something to check the response status of the URL and also the response data type (I am under the impression that Microlink needs the URL to return HTML data.)

Kikobeats commented 5 years ago

Actually, this can be achieved by moving the fetch workflow out of the SDK library.

Just make the API request in your code and pass the data from the response to the component using data field.

That's what we do in the microlink website for avoiding fetching the same payload more than once: https://github.com/microlinkhq/www/blob/master/src/components/patterns/LiveDemo/preview.js#L66

DevoKit commented 5 years ago

Hi @Kikobeats thanks for all your help! I was actually able to achieve the results I wanted using React componentDidCatch(error,errorMessage). https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html.

Kikobeats commented 5 years ago

🤯, that's smart!