Home > OS >  Update one property in MongoDB and update UI without refresh the page
Update one property in MongoDB and update UI without refresh the page

Time:05-07

I am trying to update one property Like I have a few properties, product name, price, quantity, supplier, and description. I am sending all the updated quantities with all properties to MongoDb, in that case, I am able to update the database and UI without any refresh.

const handleDelivered = (id) => {
        
        const newQuantity = (quantity - 1);
        if (newQuantity >= 0) {
            const newService = {...serviceDetail, quantity: newQuantity}
            setServiceDetail(newService);
            const url = `https://intense-tor-77999.herokuapp.com/item/${id}`;

            fetch(url, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(newService),
            })
                .then(response => response.json())
                .then(data => {
                    console.log('Success:', data);                
                })
                .catch((error) => {
                    console.error('Error:', error);
                }) 
        }
        else{
            toast(`${productName} is sold out`);
        }
    } 

But I just want to update only one property for example only quantity like

const updateQuantity = { quantity : newQuantity};

So, how can I update this one property without sending all properties from my frontend to backend?

CodePudding user response:

Firstly you can declare const [isReload, setIsReload]= useState(true);

when you get response from database after uploading new quantity, add this

.then(response => response.json())
            .then(data => {
                console.log('Success:', data); 
                  setIsReload(!isReload);               
            });

than you put isReload as dependency of useEffect, where you load data by id

    useEffect(()=>{
       fetch(url)
        .then(res=>res.json())
      .then(data => setData(data))
    },[isReload ]);

try it

  • Related