Nat
Nat

Reputation: 749

Cloudinary return empty url on first try

It is strange that whenever I restart the ReactJS and click on postDetails, it always returns an empty URL, and if I click again it returns the URL path of the image. Am I missing something in this code here. many thanks in advance and greatly appreciated.

const Addpost = () => {
    const [photo, setPhoto] = useState("")
    const [photoURL, setPhotoURL] = useState("")

    const postDetails = () => {
        const data = new FormData()
        data.append("file", photo)
        data.append("upload_preset", "xxxxx")
        data.append("cloud_name", "xxxxx")

        fetch("https://api.cloudinary.com/v1_1/xxxxx/image/upload",{
            method: "POST",
            body: data
        })
            .then(res => res.json())
            .then((data) => {       
                setPhotoURL(data.url) 
            })
            .catch(err => {
                console.log(err)
            })
    }

    return (
        <React.Fragment>
            <input
                type="file"
                className="form-control-file"
                id="photo"
                name="photo"
                onChange={(e) => setPhoto(e.target.files[0])}
            />

            <button
                type="submit"
                className="btn btn-primary btn-block"
                onClick={postDetails}
            >
                Submit
            </button>
        </React.Fragment>
    )
}

Upvotes: 0

Views: 133

Answers (1)

lala
lala

Reputation: 1439

try to do async await then (setPhotoUrl() will only be updated once the fetch get something or console.log('No data fetched!')):-

const postDetails = async() => {
  const data = new FormData()
  data.append("file", photo)
  data.append("upload_preset", "xxxxx")
  data.append("cloud_name", "xxxxx")

  let res = await fetch("https://api.cloudinary.com/v1_1/xxxxx/image/upload",{
    method: "POST",
    body: data
  })
  if(!res) console.log('No data fetched!')

  let data = res.json()
  setPhotoURL(data.url)
}

Upvotes: 1

Related Questions