0

been getting errors trying to get the url hostname from the response of the API even after I try to JSON.stringify the url since it works ok when I use a regular typed out url, any way of getting around this?

the error I get is Uncaught TypeError: Failed to construct 'URL': Invalid URL

const Articles = props => {

    const [article, setArticle] = useState([]);
        
        useEffect(() =>{
            axios.get(`https://example.com/item/${props.source}.json`)
            .then((response)=>{
                console.log(response)
                setArticle(response.data)
            })
        }, [])

let articleUrl = JSON.stringify(article.url)
const url = new URL(articleUrl);

    return(
        
            <div>
                <h1>{article.title}</h1>
                <a href={article.url}>
                <p>{url.hostname}</p>
                </a>
            </div>
        
)}

export default Articles

2 Answers2

0

The argument you pass to URL should be a string containing a URL.

You are passing it a string containing JSON.

Don’t convert it to JSON!

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • is there a way to pass in anything other than a true url when I only have an ***article.url*** ? I tried with just article.url but got the same problem – user14326313 Sep 23 '20 at 09:44
  • Then `article.url` isn’t a URL. You are initialising `article` to `[]` so it will be initially `undefined`. Probably you should test for that. – Quentin Sep 23 '20 at 09:47
0

Try not creating new URL instance after useEffect. It will not update immediately. Kindly read this (https://stackoverflow.com/a/58877875/11646865)

const Articles = props => {

  const [article, setArticle] = useState([]);
  const [url, setUrl] = useState([]);
      
      useEffect(() =>{
          axios.get(`https://example.com/item/${props.source}.json`)
          .then((response)=>{
              console.log(response)
              setUrl(new URL(response.data.url))
              setArticle(response.data)
          })
      }, [props.source])

  return(
      
          <div>
              <h1>{article.title}</h1>
              <a href={article.url}>
              <p>{url.hostname}</p>
              </a>
          </div>
      
)}

export default Articles
Eran Amarante
  • 63
  • 1
  • 7
  • makes sense, was having an issue with the updating as well! this did it, was looking into making another state for the url but wasnt even thinking about placing the new URL inside the call. thanks for the help! – user14326313 Sep 23 '20 at 10:00