简体   繁体   中英

Why I have to select 2 times (different photo) for displaying image in firebase storage

When I click uploading images first time it shows loading affect but show nothing even background image for uploading and then I have to upload different image for displaying image before submitting to go to Newfeed-page that show my account.So Iam not sure that because my code or firebase service that I have to config some rule. Thanks for helping me

import { useCookies } from "react-cookie";
import {
  ref, uploadBytesResumable, getDownloadURL, getStorage
} from "firebase/storage";
import styled from "styled-components";

const Avatar = styled.div`
width: 250px;
height: 250px;
border-radius: 50%;
background-size: cover;
background-position: center;
cursor: pointer;
`;

function Photo() {
  const [cookies] = useCookies(["userName"]);
  const [image, setImage] = useState(null);
  const [url, setUrl] = useState("./images/UploadPic.svg");

  const handleChange = (e) => {
    if (e.target.files[0]) {
      setImage(e.target.files[0]);
      const storage = getStorage();
      const storageRef = ref(storage, `images/${cookies.userName}`);
      const uploadTask = uploadBytesResumable(storageRef, image);

      uploadTask.on(
        "state_changed",
        () => {
          setUrl("./loading.gif");
        },
        (error) => {
          switch (error.code) {
            case "storage/unauthorized":
              console.log("storage is unauthorized");
              break;
            case "storage/canceled":
              console.log("storage is canceled");
              break;
            case "storage/unknown":
              console.log("storage is unknown");
              break;
            default:
              console.log("sorry it is not about storage");
          }
        },
        () => {
          getDownloadURL(storageRef).then((url) => {
            setUrl(url);
          });
        },
      );
    }
  };

  return (
    <div style={{ alignSelf: "center" }}>
      <label htmlFor="file-input">
        <Avatar style={{ backgroundImage: `url(${url})` }} />
      </label>
      <input id="file-input" type="file"  accept="image/*" onChange={handleChange} />
    </div>
  );
}

export default Photo;
<input id="file-input" type="file"  accept="image/*" onChange={handleChange} />

hey please try changing above line to below

<input id="file-input" type="file"  accept="image/*" onChange={() => handleChange()} />

not sure though worth trying

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM