Search code examples
javascriptreactjschakra-ui

How to implement progress bar properly?


So I am doing this project on React and ChakraUI to display images. My requirement is to display a progress bar whenever someone uploads an image. My problem is, when I reload the page, the progress bar works fine the first time e.g. I select an image, after selecting the image I press the upload button and the progress bar is shown. It works okay the only the first time. After that, whenever I just select the image, the progress bar gets full already. After that, clicking the upload button just uploads it. How to prevent this from happening?

import * as React from "react";

import { Button, Flex, Progress } from "@chakra-ui/react";
import { useState } from "react";
import axios from "axios";

import { baseUrl } from "../config";

function Upload(props) {
  const [selectedFile, setSelectedFile] = useState(null);
  const [curretFile, setCurrentFile] = useState(null);
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState(null);

  function fileSelectedHandler(event) {
    setSelectedFile(event.target.files[0]);
  }

  const fileUploadHandler = (event) => {
    const fd = new FormData();
    fd.append("image", selectedFile, selectedFile.name);

    axios
      .post(`${baseUrl}/upload`, fd, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
        onUploadProgress: (event) => {
          setProgress(Math.round((100 * event.loaded) / event.total));
        },
      })
      .then((res) => {
        props.onSuccessfulUpload();
        setSelectedFile(null);
        setError(null);
      })
      .catch((error) => {
        setSelectedFile(null);
        setError(error);
      });
  };

  const fileData = () => {
    if (selectedFile) {
      if (
        selectedFile.type === "image/jpeg" ||
        selectedFile.type === "image/png"
      ) {
        return (
          <div>
            {error && <div>file too large!!</div>}
            <Button colorScheme='teal' size='sm' onClick={fileUploadHandler}>
              Upload!
            </Button>
            <Progress value={progress} min='0' max='100' width='40' />
          </div>
        );
      } else {
        return (
          <div>
            <h4>Please choose an image to upload</h4>
          </div>
        );
      }
    } else {
      return (
        <div>
          <h4>Choose Photos</h4>
        </div>
      );
    }
  };

  return (
    <div>
      <input type='file' onChange={fileSelectedHandler} />
      {fileData()}
    </div>
  );
}

export default Upload;

Solution

  • I forgot to set the progress state to 0. Thanks to the fellow who reminded me to set the progress to zero.

      .then((res) => {
            props.onSuccessfulUpload();
            setSelectedFile(null);
            setError(null);
            setProgress(0); //setProgress to zero
          })