how do i post a string url to my database in a react app?

Viewed 82

I am trying to update the firebase address of an uploaded image to my sql database. I was able to get the Url of the uploaded image, but i dont know how to post the new url address to my database.

The default url shows an image, but i want to replace it with the url of the uploaded image and update the database with the new url.

this is the code i am trying to use

 setImgUrl(){
const putImgUrl={
  method: 'POST',
  headers:{
    'content-Type': 'application/json',
  },
  body: JSON.stringify({url:`${Url}`})
};
fetch('https')  }



Here is the whole js file

    import React, { useState, useEffect } from "react";
import { Paper } from "@mui/material";
import authHeader from "../../features/authentication/AuthHeader";
import { storage } from "./firebase";
import { getDownloadURL, uploadBytesResumable, ref } from "firebase/storage";
import { async } from "@firebase/util";

function UserProfile() {
  const [user, setUser] = useState({});
  const [Url, setUrl] = useState("");

  async function fetchUser() {
    const response = await fetch("http://localhost:9005/getProfile", {
      headers: authHeader(),
    });
    const fetchedUser = await response.json();
    console.log(fetchedUser);
    setUser(fetchedUser);
  }

  useEffect(() => {
    fetchUser();
  }, []);

  //firebase upload below this

  const [progress, setProgress] = useState(0);

  const handleFireBaseUpload = (e) => {
    e.preventDefault();
    const image = e.target[0].files[0];
    console.log("uploading pic");
    console.log(image);
    uploadImage(image);
  };

  const uploadImage = (image) => {
    if (!image) {
      alert(`image format not supported${typeof image}`);
      return;
    }
    const storageRef = ref(storage, `/images/${image.name}`);
    const uploadTask = uploadBytesResumable(storageRef, image);

    uploadTask.on(
      "state_changed",
      (snapshot) => {
        const prog = Math.round(
          (snapshot.bytesTransferred / snapshot.totalBytes) * 100
        );
        setProgress(prog);
      },
      (err) => console.log(err),
      () => {
        //fetching download Url
        getDownloadURL(uploadTask.snapshot.ref).then((url) => {
          setUrl(url);
          console.log(url);
          updateImgUrl(url);
        });
      }       

    );
  };

   setImgUrl(){
    const putImgUrl={
      method: 'POST',
      headers:{
        'content-Type': 'application/json',
      },
      body: JSON.stringify({url:`${Url}`})
    };
    fetch('https')
  }

  

  return (
    <>
      <paper
        elevation={6}
        style={{ flexDirection: "row", justifyContent: "flex-end" }}
        key={user.user_id}
      >
        <div className="pfp">
          <img src={user.imgUrl} height={150} alt="Profile Picture" />
          <form onSubmit={handleFireBaseUpload}>
            <input type="file" />
            <button onClick={() => (user.imgUrl = Url)}>Upload</button>
          </form>
        </div>
      </paper>

      <Paper
        elevation={6}
        style={{ margin: "10px", padding: "15px", textAlign: "left" }}
        key={user.user_id}
      >
        First Name: {user.firstName}
        <br />
        Last Name: {user.lastName}
        <br />
        Email: {user.email}
        <br />
        Phone: {user.phone}
      </Paper>
    </>
  );
}
export { UserProfile as default };

enter image description here

1 Answers

When the user clicks the Upload button you are calling the handleFireBaseUpload function but also setting user.imgUrl to the current Url from state. Your handleFireBaseUpload is asynchronous but user.imgUrl will be set immediately. The state is only going to be updated once the handleFireBaseUpload function reaches that point, so user.imgUrl will be set from the current state, which is an empty string.

Try using the Url state value as the src for the image, or set user.imgUrl inside the uploadImage function.

Related