skip to Main Content

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


  1. There are a few things wrong with your code:

    1. handlePostRequest is async and you’re not awaiting it
    2. You’re defining responseData in the try block but returning it outside the try/catch block where it doesn’t exist

    To 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 a useEffect on mount.

    import { useState } from "react";
    
    function MyImage() {
      const [src, setSrc] = useState();
    
      const handlePostRequest = async () => {
        try {
          const response = await fetch('https://api.com', {
            method: 'POST',
            body: '',
            headers: {
              'Content-Type': 'application/json',
            },
          });
    
          const responseData = await response.json();
          setSrc(responseData);
        } catch (error) {
          console.error('Error during POST request: ', error.message);
        }
      };
    
      useEffect(() => {
        handlePostRequest();
      }, []);
    
      if (!src) return <p>Loading...</p>
    
      return (
        <img src={src} loading="lazy" />
      );
    }
    
    Login or Signup to reply.
  2. 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

    const [imgSrc, setImgSrc] = useState();
    const handlePostRequest = async () => {
        try {
            const response = await fetch('https://api.com', {
                method: 'POST',
                body: '',
                headers: {
                    'Content-Type': 'application/json',
                },
            });
    
            const responseData = await response.json();
            setImgSrc(responseData)
        } catch (error) {
            console.error('Error during POST request: ', error.message);
        }
    };
    
    return (
        imgSrc && <img
            key={innerIndex}
            src={imgSrc}
            title={image.title}
            className="m-3"
            loading="lazy"
            alt={category}        
        />
    );
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search