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

183
Vistas
Cannot update product quantity stored in MongoDB, using Node.js and React.js

I am building a warehouse management site. I have the data stored in MongoDB. I want the product quantity to be updated on a button click and show it on the UI. But after updating the quantity, when I console log it I get undefined.

This is the function to decrease the quantity on click and update it on DB:

const ProductDetail = () => {
    const { productId } = useParams();
    const [product] = useProductDetail(productId);
    const { _id, name, img, description, supplier, price, quantity } = product;

    const [updatedQuantity, setUpdatedQuantity] = useState(quantity);


    const handleDecreaseQuantity = (id) => {

        const { quantity, ...rest } = product;
        const previousQuantity = quantity;
        setUpdatedQuantity(previousQuantity - 1)
        const updatedProduct = { updatedQuantity, ...rest }

        fetch(`http://localhost:5000/updateProduct/${id}`, {
            method: 'PUT',
            headers: {
                "content-type": "application/json"
            },
            body: JSON.stringify(updatedProduct)
        })
            .then(res => res.json())
            .then(data => {
                console.log(data)
            })
        console.log(updatedQuantity);

    }

This is product update API:

app.put('/updateProduct/:id', async (req, res) => {
            const updatedProduct = req.body;
            const { updatedQuantity } = updatedProduct;
            const id = req.params.id;
            const query = { _id: ObjectId(id) };
            const options = { upsert: true };

            const updateProduct = {
                $set: {
                    quantity: updatedQuantity
                },
            };

            const result = await productCollection.updateOne(query, updateProduct, options);
            console.log(result);

            res.send(result);

        })

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

setState actions are asynchronous and are batched for performance gains. This is explained in the documentation of setState.

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

This part of the code might not be executing as you think.

const previousQuantity = quantity;
setUpdatedQuantity(previousQuantity - 1);
const updatedProduct = { updatedQuantity, ...rest };

Update your product quantity and send it to API. By the action is completed, your state also might be updated.

const previousQuantity = quantity;
const updatedProduct = { updatedQuantity: previousQuantity - 1, ...rest };
setUpdatedQuantity(previousQuantity - 1);
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