Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

271
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda