Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

268
Views
cann't decrease a value by one in the UI with node.js mongodb, react

I am trying to update a value in the UI. When I click to update, I have a button that will decrease by one In the database and be displayed in the UI's quantity section. when I click on the button, it's decreased by one, but it doesn't decrease if click again.

UI images enter image description here

//getting the data in the useEffectm updating quantity in handleUpdate

const { bookId } = useParams();
    const [book, setBook] = useState({});
    const [reload, setReload] = useState(true);
    console.log(reload);

    useEffect(() => {
        const url = `url/book/${bookId}`;
        fetch(url)
            .then(res => res.json())
            .then(data => setBook(data))
    }, [reload])

    const quantity = parseInt(book.quantity) - 1;
    console.log(quantity);


    const handleUpdate = () => {
        const url = `url/books/${bookId}`
        fetch(url, {
            method: "PUT",
            headers: {
                'content-type': 'application/json'
            },
            body: JSON.stringify({ quantity })
        })
            .then(res => res.json())
            .then(data => {
                console.log(data)
                setReload(!reload)
                alert("user updated")
            })
    }
//API for updating the value.
 // update quantity 
        app.put('/books/:id', async (req, res) => {
            const id = req.params.id;
            console.log(req.body)
            const quantity = req.body.quantity
            console.log(quantity)
            const filter = { _id: ObjectId(id) };
            const options = { upsert: true };
            const updatedQuantity = {
                $set: { ...quantity - 1}
            }
            const result = await bookCollections.updateOne(filter, updatedQuantity, options);
            res.send(result);
        });
//displaying the updated value
<li className="m-1">
<Link className="inline-flex text-center text-gray-100 py-1 px-3 rounded-full bg-blue-500 hover:bg-blue-600 transition duration-150 ease-in-out" to="#0">Quantity: {quantity}</Link>
</li>
//calling the function in button.
<button onClick={handleUpdate} className="btn btn-outline text-white">Delevered</button>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

When decreasing the value by one, try storing it in a state. And use the current value from database as the default value of the state. for example,

const [newQuantity, setNewQuantity] = useState(product.quantity);

after fetching, set the new value like this:

fetch(url, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(updatedQuantity)

    })
        .then(res => res.json())
        .then(data => {
            setNewQuantity(updatedQuantity);
        })
}
about 4 years ago · Juan Pablo Isaza Report

0

You are almost done. In server side just destructure the quantity as it is already updated. it should look like,

 $set: {...quantity}

and in onClick function pass id both during defining function and calling function inside button

onClick={()=> handleUpdate(bookId)} 

It should work:)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!