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

279
Views
no se puede disminuir un valor en uno en la interfaz de usuario con node.js mongodb, reaccionar

Estoy tratando de actualizar un valor en la interfaz de usuario. Cuando hago clic para update , tengo un botón que disminuirá en uno en la base de datos y se mostrará en la sección de quantity de la interfaz de usuario. cuando hago clic en el botón, disminuye en uno, pero no disminuye si hago clic nuevamente.

Imágenes de la interfaz de usuario ingrese la descripción de la imagen aquí

 //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

Al disminuir el valor en uno, intente almacenarlo en un estado. Y use el valor actual de la base de datos como el valor predeterminado del estado. por ejemplo,

const [nuevaCantidad, establecerNuevaCantidad] = estadoUso(producto.cantidad);

después de obtener, establezca el nuevo valor de esta manera:

fetch(url, {método: 'PUT', encabezados: {'tipo de contenido': 'aplicación/json'}, cuerpo: JSON.stringify(cantidad actualizada)

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

0

Estas casi listo. En el lado del servidor, simplemente desestructura la cantidad, ya que ya está actualizada. debería verse como,

 $set: {...quantity}

y en la función onClick pase la identificación tanto durante la definición de la función como durante la función de llamada dentro del botón

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

Deberia de funcionar:)

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!