2021年1月6日星期三

Accessing useState state inside a Cloudinary upload widget callback

I'm using the Cloudinary upload widget inside a React component to upload images, and I'll like to run some code once those images are uploaded:

const showWidget = (e) => {      e.preventDefault();  const widget = window.cloudinary.createUploadWidget(        {          cloudName,          uploadPreset,        },        uploadCallback: () => { // do stuff here... }      );      widget.open();    };  

My issue is that the component's state (defined using useState) doesn't seem to be properly available inside uploadCallback():

const [ uploaded, setUploaded ] = useState([]);    const uploadCallback = (error, result) => {    setUploaded([...uploaded, ...result.photos]);  }  

The callback can trigger multiple times (once every time an image is finished uploading), and I wanted to add the uploaded image to the state each time, but inside the callback uploaded is always equal to its default value of [], meaning each call to setUploaded() overwrites it instead of adding to it.

Is there a way to make this callback work with React state properly? Or does it boil down to how the callback is called by the widget library and there's not much I can do about it?

https://stackoverflow.com/questions/65605326/accessing-usestate-state-inside-a-cloudinary-upload-widget-callback January 07, 2021 at 09:04AM

没有评论:

发表评论