how do i get the onuploadprogress value in an await function from axios?

Generally, I’d advise using some kind of state management (redux/mobx) for controlling this flow. Not to handle it directly from a React component. So the component will trigger a kind of action and the upload process will be handled outside.

But, for a very simple solution, you’d need something like this:

function uploadImage(file, updateProgress) {
  return'/api/media_objects', file, {
    onUploadProgress: progressEvent => {
      let percentComplete = progressEvent.loaded /
      percentComplete = parseInt(percentComplete * 100);
  }).then(response =>;

    const MyComponent = () => {
       const [progress, setProgress] = useState(0);
       const onUpload = useCallback(() => {
             myApi.uploadImage(data, setProgress);

       return <div>
                   <span>Uploaded: {progress}</span>
                   <button onClick={onUpload}>Upload</button>

the progress value is stored in the component’s state so it can be updated and rendered.

I would also put the try/catch in the API method rather than in the component.

On a more general note. I’d advise using a library such as react-uploady to manage the upload for you. There’s are a lot of edge cases and functionality you need to handle typically when uploading files and a small 3rd party like Uploady takes care of it for you: Preview with progress for file uploading in React

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top