In my React project, I need to send a POST request to an API, the API will respond with an URL, and I want to use this URL as the src
attribute of an image tag. The following is the conceptual work flow, which of course does not work. I wonder what is the correct way to write the code. Any help are highly appreciated!
const handlePostRequest = async () => {
try {
const response = await fetch('https://api.com', {
method: 'POST',
body: '',
headers: {
'Content-Type': 'application/json',
},
});
const responseData = await response.json();
} catch (error) {
console.error('Error during POST request: ', error.message);
}
return responseData;
};
ImgSrc = handlePostRequest();
return (
<img
key={innerIndex}
src={ImgSrc}
title={image.title}
className="m-3"
loading="lazy"
alt={category}
/>
);
2
Answers
There are a few things wrong with your code:
handlePostRequest
isasync
and you’re not awaiting itresponseData
in thetry
block but returning it outside thetry/catch
block where it doesn’t existTo make this work in a React-friendly way, you’d need to use a stateful variable with
useState
and introduce a loading state while your request is in flight, which would be triggered by auseEffect
on mount.the issue is happening because the value of handlePostRequest has been assigned to the variable before it’s resolved. You can fix the issue as follows: if you are sending a GET request, then you can follow the implementation mentioned by @emeraldsanto using a useEffect. However, a correction has to be mentioned in that answer because variables inside a try block can be accessed outside
This would re-render the DOM once the data is fetched, and the image will be shown via the img tag.
Tip: Usually, most React developers use lowerCamelCase to name variable names, and UpperCamelCase is used only to define components and their files.