I am posting an image to my Cloudinary account and want to save the URL from the response in the imageUrl
state. When console logging the response URL, it shows me the Cloudinary URL correctly but the setImageUrl
doesn't seem to be working.
I have changed my Cloudinary details to 'dummy' for security reasons
import React, { useState } from "react";
import "./image.css";
function Image() {
const [image, setImage] = useState("");
const [imageUrl, setImageUrl] = useState("");
const postDetails = async () => {
const data = new FormData();
data.append("file", image);
data.append("upload_preset", "dummy");
data.append("cloud_name", "dummy");
const settings = { method: "POST", body: data };
try {
const fetchData = await fetch(
"https://api.cloudinary.com/v1_1/dummy/image/upload",
settings
);
const resData = await fetchData.json();
console.log(resData.url);
if (resData) {
setImageUrl(resData.url);
console.log("imageUrl", imageUrl);
}
} catch (e) {
console.log(e);
}
};
return (
<>
<div className="file-field input-field">
<div className="btn #64b5f6 blue darken-1">
<span>Uplaod Image</span>
<input type="file" onChange={(e) => setImage(e.target.files[0])} />
</div>
<div className="file-path-wrapper">
<input className="file-path validate" type="text" />
</div>
</div>
<button
className="btn waves-effect waves-light #64b5f6 blue darken-1"
onClick={() => postDetails()}
>
Submit post
</button>
</>
);
}
export default Image;
{imageUrl}
and can see it is setting, thanks – Matt Apr 30 '22 at 16:07