0

In React Javascript, I am calling a function and then trying to console.log() what that function returns. However, the log is called before the function finishes. I am trying to fetch a post API but synchronously.

const uploadImage = (img) => {
  let resImg = null;
  const imgAPIKey = "process.env.IMGBBKEY";
  let formData = new FormData();
  formData.append("image", img);
  const url = `https://api.imgbb.com/1/upload?key=${imgAPIKey}`;
  console.log(formData);
  fetch(url, {
    method: "POST",
    body:
      formData,
  })
    .then((res) => res.json())
    .then((result) => {
      resImg = result.data.display_url;
      console.log(resImg);
      console.log("imgbb", result);
      return resImg;
    });
};


const WorkforceForm = () => {
  const httpClient = useHttpClient();
  const navigate = useNavigate();

  const testSubmit = () => {
    const imgData = uploadImage(img1);
    console.log(imgData);
  };

return <button onClick={testSubmit}>SUBMIT</button>;
};

This logs the value of resImg in the uploadImage function before being called synchronously in testSubmit()

Any idea how to make the uploadImage finish before proceeding to log the value it assigns to imgData?

const testSubmit = () => {
    const imgData = uploadImage(img1);
    console.log(imgData);
  };
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) A `fetch` call is asynchronous by nature, you cannot change that. – Heiko Theißen Oct 06 '22 at 15:27

0 Answers0