skip to Main Content

I’m trying to use file upload with preview and this is the code of my component:

const [uploadField, setUploadFiled] = useState()

useEffect(() => {
    const temp = new FileUploadWithPreview('fileUpload', {
        multiple: multiple,
    });
    window.addEventListener(Events.IMAGE_ADDED, (e) => {
        const { detail } = e;
        console.log('detail', detail);
    });
}, [])

The problem is that since I have <React.StrictMode> I see two file upload controls in my page. And whenever I save the file, because of HMR another control would be created.

I want to only run that initialization code once.

How can I achieve that?

2

Answers


  1. You can use the useRef hook to store a reference to the FileUploadWithPreview instance.

    This will ensure that the code is only executed once, even when HMR is enabled.

    const uploadFieldRef = useRef();
    useEffect(() => {
        const temp = new FileUploadWithPreview('fileUpload', {
            multiple: multiple,
        });
    
        uploadFieldRef.current = temp;
    
        window.addEventListener(Events.IMAGE_ADDED, (e) => {
            const { detail } = e;
            console.log('detail', detail);
        }); 
    }, []);
    
    Login or Signup to reply.
  2. try useRef hook

     const effectCalled = useRef(false);
    
      useEffect(() => {
        if (effectCalled.current) return;
        console.log("app rendered");
        effectCalled.current = true;
      }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search