Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

javascript - Getting file from MaterialUI Upload Button to React Hook and uploading to Firestorage?

Hey guys I am using MaterialUI's Upload Button from here: https://material-ui.com/components/buttons/

As you can see below I have copy pasted that button and now I want to upload it to Firebase Firestorage using my hook. By pressing on the button it class changeFoto

  <input
            accept="image/*"
            className={classes.input}
            id="contained-button-file"
            multiple
            type="file"
            onChange={(e) => changeFoto(e)}
          />
          <label htmlFor="contained-button-file">
            <Button className={classes.fotoButton} component="span">
              Foto
            </Button>
          </label>

Here you can see the changeFoto function:

(setFoto is a hook in this case and foto the variable of the useState)

const changeFoto = (e) => {
    setFoto(e.target.files[0]);
    const pflegeengelRef = storage.child(
      "pflegeengel/" + pflegeengelDocumentIDs[selectedIndex]
    );
    pflegeengelRef.put(foto).then(function (snapshot) {
      console.log("Uploaded a file!");
    });
  };

And indeed something gets uploaded when I go look into the storage there is a file. But it is not my image file it was some weird file format that only had the text "undefined" in it. So that is my problem I guess


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This happens because setFoto is an async function. It doesn't update foto immediately - it triggers a render with the new foto as the new value.

When you try to upload foto, it hasn't updated yet. Using put(e.target.files[0]) would solve your problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...