Reactjs Put request

I am trying to create a PUT request system i have work on it for a couple of hours to make it work but it has been a complete drama, sometimes the code work and sometimes it doesnt. I feel like this could be code way better and more efficient .

the idea is that it should only update the fields that are not empty and not update the empty fields.

const edit = async () =>{
    const[status,setStatus] = useState("");
    const[name,setName] = useState(null);
    const[description,setDescription]= useState(null);
    const[price,setPrice] = useState(null);
    const[category,setCategory] = useState(null);
    const[file, setFile] = useState(null);
    const inputRef2 = useRef(null);

const edit = async () =>{
    const formdata = new FormData();
    
let senddata = formdata

    if(file !== null){ formdata.append("file",file, file.name);  }
    if(name === null){formdata.append("name", " ");}
    if(description === null){formdata.append('description'," ");}
    if(price === null){formdata.append('price'," ");}
    if(category === null){formdata.append('category'," ");}

let object = {
    name: name,
    description : description,
    price: price,
    category: category,
    file: null
}

if(name === null){ object.name = " ";}
if(description === null){ object.description = " ";}
if(price === null){ object.price = -1;}
if(category === null){ object.category = " ";}

  if(file === null){  senddata = object; }

  console.log(senddata)

  const res = await  axios.put(url,senddata)
    if(res.status === 200) {
        setStatus("Product has been succesfuly updated") }
    else{
        setStatus("Product has Failed to update")  }
       
}

return (
//other coder and fields
<input type="file" name="editpicture" onChange={(e) => setFile(e.target.files[0])}  ref={inputRef2}/></p>
<button onClick={edit}>Save chances</button>
//other coder and fields
)

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.