Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda