kqito / use-tus

React hooks for resumable file uploads using tus
https://kqito.github.io/use-tus/?path=/story/usetus--basic
MIT License
104 stars 8 forks source link

Extend methods of referencing `upload` on react lifecycle #47

Closed kqito closed 1 year ago

kqito commented 1 year ago

Overview

◦ Made changes to re-rendering when the url field of the upload instance is changed ◦ Modified to allow receiving the upload instance as the last argument of various callbacks

related: https://github.com/kqito/use-tus/issues/46

[BREAKING CHANGE] Re-rendering when the url field is changed

The upload that can be generated using tus-js-client is an instance of the Upload class. Until now, I avoided re-rendering in response to changes in the upload instance, as it was feared that this would lead to excessive rendering.

However, I anticipate cases where I want to refer to the url according to the react lifecycle, so I have made changes to allow re-rendering when the url field is changed

e.g.

  useEffect(() => {
    console.log("useEffect", upload?.url);
  }, [upload?.url]);

[BREAKING CHANGE] Referencing upload within callback

Until now, it was impossible to refer to upload within callbacks such as onSuccess in useTus hooks and useTusStore hooks unless useRef was used.

const { upload, setUpload } = useTus()
const uploadRef = useRef()
uploadRef.current = upload

// .....

const handleSetUpload = (event: ChangeEvent<HTMLInputElement>) => {
  const file = event.target?.files?.item(0);
  if (!file) {
    return;
  }

  setUpload(file, {
    onSuccess: () => {
      console.log(uploadRef.current);
    },
  });
};

After considering various implementation methods, I adopted the method of extending to allow referencing the upload instance as the last argument of the existing callback.

e.g.

setUplaod(file, {
  onSuccess: (upload) => {
    console.log(upload.url)
  },
  onError: (error, upload) => {
    console.log(error)

    setTimeout(() => {
      upload.start()
    }, 1000)
  }
})

Despite the rising concerns regarding the complexity and version restrictions that come with maintaining a different interface compared to tus-js-client, I understand this implementation method stands out as the simplest and most necessary means of referencing upload within the React lifecycle.