Search code examples
reactjsvariables

'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

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>   );