Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

'imgSrc' is not defined no-undef

Consider this:

useEffect(() => {
    let imageUrlRequest = axios.get(imageEndPointString).then(function (response) {
        console.log('call made')
        let imgSrc = response.data[0].data.children[0].data.url;
        console.log(imgSrc)
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });
  },[]);

  return (
    <div className="game__image">
      <h2>IMAGE URL: {imgSrc}</h2>
      <img src={imgSrc} />
    </div>
  );

Howcome imgSrc is undefined?

I also tried this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let imgSrc;

  useEffect(() => {
    let imageUrlRequest = axios.get(imageEndPointString).then(function (response) {
        console.log('call made')
        imgSrc = response.data[0].data.children[0].data.url;
        console.log(imgSrc)
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });
  },[]);

  return (
    <div className="game">
      <img src={imgSrc} />
    </div>
  );

but the image still won’t come through. why?

>Solution :

In Javascript variables that are declared inside a block can be used only in this block (local scope).
Furthermore, in React if you want to change your view based on some value you must use the setState function to allow React to know when it should re-render the view.

So in your example you need to do something like this:

const [imgSrc, setImgSrc] = useState(null);

useEffect(() => {
    let imageUrlRequest = axios.get(imageEndPointString).then(function (response) {
        console.log('call made')
        setImgSrc(response.data[0].data.children[0].data.url);
        console.log(imgSrc)
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });   },[]);

  return (
    <div className="game__image">
      <h2>IMAGE URL: {imgSrc}</h2>
      <img src={imgSrc} />
    </div>   );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading