Recommand · October 14, 2021 0

Why is setState callback state turning to "undefined" after populated with data?

I am trying to create a product with an image from browser. For the image field, I have a separate component to crop the image.

       // pass setImage as callback to child FileLoader component
       const [image, setImage] = useState("");

       
       // part of createProduct form.
       // this is a separete component. i passed callback to the set the image url
      <FileLoader onFileUpload={setImage}></FileLoader>
      
      <Form.Group controlId="brand">
        <Form.Label>Brand</Form.Label>
        <Form.Control
          type="text"
          placeholder="Enter brand"
          value={brand}
          onChange={(e) => setBrand(e.target.value)}
        ></Form.Control>
      </Form.Group>

My goal is to set the image, upload it first to Django, Django will return the url for S3 bucket, I will use that url to pass along with the createProduct form. inside FileLoader component, this is how I send the post request:

 const uploadFileHandler = async (image: File) => {
    const formData = new FormData();
    formData.append("image", image);
    const config = {
      headers: {
        "Content-Type": "multipart/form-data",
        Authorization: `Bearer ${userInfo?.token}`,
      },};
    return axios
      .post(
        `${process.env.DJANGO_API_URL!}/api/products/upload-image/`,
        formData,
        config )
       // onFileUpload is callback to set the image in parent component
      .then((res) => onFileUpload(res.data));
  };

This actually works. I get the url but as soon as I get it, it becomes undefined. What could be the reason? I also logged the "name" of the product and that state still persisted and also posted to the backend when I submit the form

enter image description here