簡體   English   中英

如何在 Promise Javascript/React 中調用 API

[英]How to call API inside a Promise Javascript/React

目標:在將它的路徑設置為cloudinary之前,我需要從 cloudinary 獲取image_url 所以我創建了一個 Promise 並嘗試執行以下操作:

export const uploadToCloudinary = (imageData, setImageURL) => {
  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);
        setImageURL(responseData.secure_url);
      })
      .catch(error => {
        console.log(`[ERROR] While trying to upload: ${error.message}`);
        setImageURL(null);
      });
  } else {
    setImageURL(null);
  }
};

組件.js

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

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

控制台 output:

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

如果我選擇一個圖像,那么在 promise 得到解決之后,那么只有它應該setImageURL對嗎? (因此破壞了整個目的)。 我在這里做錯了什么?

您無需等待 uploadToCloudinary(image, setImageURL),因此其下方的 console.log 為 null。

我會做這樣的事情:

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

  useEffect(() => {
    if (imageURL) {
      setMessage({
      ...someData,
      image: imageURL, // hence image: null,
    });
    setImageURL(null);
  }
  }, [imageURL]);

  const sendMessage = () => {
      Keyboard.dismiss();
      if (input || image) {
        uploadToCloudinary(image, setImageURL);        
      }
    };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM