0

I am try to update data through Method:PUT using (fetch) in React and backend at Django-Rest-Framework.

This Code for fetch method put

    const url  = '/productapi/';

    const id = props.id;
    const [name,setName] = useState('');
    const [price,setPrice] = useState('');
    const [quantity,setQuantity] = useState('');

    
    const handleUpdate = (e) => {
        e.preventDefault();
        fetch(url,  {
            headers:{
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            method:'PUT',
            body: JSON.stringify({
                id:id,
                name:name,
                price:price,
                quantity:quantity,
            }) 
        })
        .then(data=>{
            console.log(product);
        });
    }

I am trying to update data through form

<form className="addPro" onSubmit={handleUpdate}>
   <label>Name:</label>
   <input type="text" value={name}  onChange={(e) => setName(e.target.value)} />
   <br />
   <label>Price:</label>
   <input type="float" value={price}  onChange={(e) => setPrice(e.target.value)} />
   <br />
   <label>Quantity:</label>
   <input type="integer" value={quantity}  onChange={(e)=>setQuantity(e.target.value)} />
   <br />
   <input className="submitBtn" type="submit" />
</form>`

I want to update according to data inputted in form,I only want to update inputted data in any of field. And not want to pass empty field/null data to fetch body.

  • You could just filter trough object like here: https://stackoverflow.com/questions/286141/remove-blank-attributes-from-an-object-in-javascript – Loki Nov 07 '22 at 18:50
  • If you want force the user to enter something you can add the `required` prop to your input – RubenSmn Nov 07 '22 at 18:52

0 Answers0