Skip to content

Commit

Permalink
add cleanup function
Browse files Browse the repository at this point in the history
  • Loading branch information
JoshuaRotimi committed Oct 11, 2023
1 parent 0e176f7 commit 8df4ac5
Showing 1 changed file with 20 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { useEffect } from 'react';
import { useEffect, useRef } from 'react';

let cloudinary;
let widget;


const UploadWidget = ({ children, onUpload }) => {

const widget = useRef();
useEffect(() => {
// Store the Cloudinary window instance to a ref when the page renders

Expand All @@ -17,13 +18,17 @@ const UploadWidget = ({ children, onUpload }) => {
// setTimeout: https://caniuse.com/requestidlecallback

function onIdle() {
if ( !widget ) {
widget = createWidget();
if ( !widget.current ) {
widget.current = createWidget();
}
}

'requestIdleCallback' in window ? requestIdleCallback(onIdle) : setTimeout(onIdle, 1);

return () => {
widget.current?.destroy();
widget.current = undefined;
}
// eslint-disable-next-line
}, []);

Expand All @@ -38,9 +43,15 @@ const UploadWidget = ({ children, onUpload }) => {
// "unsigned" uploads which may allow for more usage than intended. Read more
// about unsigned uploads at: https://cloudinary.com/documentation/upload_images#unsigned_upload

const cloudName = process.env.REACT_APP_CLOUDINARY_CLOUD_NAME;
const uploadPreset = process.env.REACT_APP_CLOUDINARY_UPLOAD_PRESET;

if (!cloudName || !uploadPreset) {
console.warn(`Kindly ensure you have the cloudName and UploadPreset setup in your .env file at the root of your project.`)
}
const options = {
cloudName: process.env.REACT_APP_CLOUDINARY_CLOUD_NAME, // Ex: mycloudname
uploadPreset: process.env.REACT_APP_CLOUDINARY_UPLOAD_PRESET, // Ex: myuploadpreset
cloudName, // Ex: mycloudname
uploadPreset, // Ex: myuploadpreset
}

return cloudinary?.createUploadWidget(options,
Expand All @@ -62,10 +73,10 @@ const UploadWidget = ({ children, onUpload }) => {
*/

function open() {
if ( !widget ) {
widget = createWidget();
if ( !widget.current ) {
widget.current = createWidget();
}
widget && widget.open();
widget.current && widget.current.open();
}

return (
Expand Down

0 comments on commit 8df4ac5

Please sign in to comment.