in

How to call API inside a Promise Javascript/React


Aim: I need to get image_url from cloudinary before setting it’s path to a state. So I created a Promise and tried to do the following:

export const uploadToCloudinary = (imageData, setImageURL) => {
  return new Promise((resolve, reject) => {
    if (imageData) {
      const data = new FormData();
      data.append('file', imageData);
      
      fetch(CLOUDINARY_BASE_URL, {
        method: 'POST',
        body: data,
      })
        .then(response => response.json())
        .then(responseData => {
          console.log('api: ',responseData.secure_url); // THIS PRINTS LATER, BECAUSE IT IS A PROMISE
          setImageURL(responseData.secure_url);
        })
        .catch(error => {
          console.log(`[ERROR] While trying to upload: ${error.message}`);
          setImageURL(null);
        });
    }
    resolve();
  });
};

component.js

const [imageURL, setImageURL] = useState(null);

const sendMessage = () => {
    Keyboard.dismiss();
    if (input || image) {
      uploadToCloudinary(image, setImageURL).then(() => {
        console.log(imageURL); // THIS PRINTS FIRST & obviously it is null.
        const message = {
          ...someData,
          image: imageURL, // hence image: null,
        };
        setImageURL(null);
      });
    }
  };

console output:

LOG: null
LOG: https://res.cloudinary.com/abcd/image/upload/v12324/luxjoasdceavl8asdc2dxb.jpg

If I’m selecting an image, then after the promise gets resolved, then only it should setImageURL right? (hence defeating the whole purpose). What am I doing wrong here?



Source: https://stackoverflow.com/questions/70611152/how-to-call-api-inside-a-promise-javascript-react

AWS Releases Multi-Cloud Kubernetes Autoscaler Karpenter

a simple and efficient package to send emails