0

It must be basic but please help me understand why this doesn't work.

When I write a normal arrow function and return jsx, it works. But, when I use async/await request with the same arrow function to return jsx, it fails.

Edit:

Actually I have to show profile images of users inside a list view. So, I am calling this function to retrieve the images of the respective users inside my render() {return } block

This works

handleProfilePhoto = firstName => {
        return (
            <img
                className="comment-img"
                src={require("../../../../Webroot/images/dashboard/image3.png")}
                alt={firstName + " profile"}
            />
        );
    };

And this doesn't

handleProfilePhoto = async (firstName) => {
        let err = false;

        await Axios
            .get(MY_URL)
            .then(function () {
                err = false;
            })
            .catch(function () {
                err = true;
            });

        return err === true ? (
            <img
                className="comment-img"
                src={require("../../../../Webroot/images/dashboard/image3.png")}
                alt={firstName + " profile"}
            />
        ) : (
            <img
                className="comment-img"
                src={require("../../../../Webroot/images/dashboard/image4.png")}
                alt={firstName + " profile"}
            />
        );
    };
Chilarai
  • 1,842
  • 2
  • 15
  • 33

1 Answers1

1

Please do not use .then() with async / await you either use the chainging or the async way.

handleProfilePhoto = async (firstName) => {
        let err = false;
      
        try {
           await Axios.get(MY_URL);
        } catch(err) {
           err = true;
        } 
        return err === true ? (
            <img
                className="comment-img"
                src={require("../../../../Webroot/images/dashboard/image3.png")}
                alt={firstName + " profile"}
            />
        ) : (
            <img
                className="comment-img"
                src={require("../../../../Webroot/images/dashboard/image4.png")}
                alt={firstName + " profile"}
            />
        );
    };

Also, handleProfilePhoto returns an promise.

handleProfilePhoto.then(result => {
   //your result is here
})
bill.gates
  • 14,145
  • 3
  • 19
  • 47