'image file isnt being read by react

I am using formData to send details to my backend but somehow my image path isn't being sent.

           Post photo
              <div className="form-group">
                <label className="btn btn-block btn-success">
                  <input
                    onChange={handleChange("photo")}
                    ref={inputRef}
                    type="file"
                    name="photo"
                    accept="image"
                    placeholder="choose a file"
                  />
                </label>
              </div>

this is the form i am using

Handle change and submit button

const onSubmit = (event) => {
                event.preventDefault();
                setValues({...values,error:"",loading:true});
                createProduct(user._id,token,JSON.stringify(values))
                .then(data=>{
                  if(data.error){
                    setValues({...values,error:data.error});
                  }else{
                    setValues({...values,
                      name:"",
                      description:"",
                      price:"",
                      photo:"",
                      stock:"",
                      createdProduct:data.name,
                      loading:false});
                  }
                }).then(response=>{
                   
                })
                .catch(err=>console.log(err));
        //
      };
    
const handleChange = name => event => {
  const value=name==="photo"?event.target.files[0]:event.target.value;
  formData.append(name,value)
  setValues({...values,[name]:value});
        //
}; 

And this is the api call to backend

export const createProduct=(userId,token,product)=>{
console.log(product)
  return fetch(`${API}/product/create/${userId}`,{
    method: "POST",
    headers:{
      Accept: "application/json",
      Authorization: `Bearer ${token}`
    },body:product
  })
  .then(response=>{
    return response.json();
  })
  .catch(err=>console.log(err));
}

The api is working fine with postman , I am using formidable in backend. Some answers from stack made the path of the file have c:\fakepath and so m too confused what to do . Thanks for help.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source