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

105
Vistas
MongoDB keeps returning one less value than intended value

I am currently working on a blog project where I have to enable a "liking" feature on my blog website. I have enabled the liking feature, however, whenever I test the liking feature with my MongoDB, the response I get is always a like that is one less than the intended value. For example, if I give a blog a like, that already has 4 likes, I get back a document only showing the 4 likes and not the updated document with the new 5 likes.

Here is my frontend code that deals with the "liking" feature:

import axios from "axios"
import { useEffect, useState } from "react"
import blogService from '../services/blogs'
const baseUrl = '/api/blogs'

const Blog = ({blog}) => {
  const [checker, setChecker] = useState(false)
  const [blogLikes, setBlogLikes] = useState(0)
  const [updatedBlog, setUpdatedBlog] = useState({})
  const buttonText = checker  ? 'hide' : 'view'

  useEffect(() => {
    setUpdatedBlog({
      user: blog.user?.id,
      likes: blogLikes,
      author: blog.author,
      title: blog.title,
      url: blog.url
    })
  }, [blogLikes])
  
  
  const blogStyle = {
    paddingTop: 10,
    paddingLeft: 2,
    border: 'solid',
    borderWidth: 1,
    marginBottom: 5
  }

  const handleLike = async (e) => {
    e.preventDefault()

    setBlogLikes(blogLikes + 1)
    
    const response = await blogService.update(blog?.id, updatedBlog)
    console.log(response)

  }

  return (
    <>
  {buttonText === "view" ?   
  <div style={blogStyle}>
    {blog.title} {blog.author} <button onClick={() => setChecker(!checker)}>{buttonText}</button>
  </div>
  : <div style={blogStyle}>
      {blog.title} {blog.author} <button onClick={() => setChecker(!checker)}>{buttonText}</button>
      <p>{blog.url}</p>
      likes {blogLikes} <button onClick={handleLike}>like</button>
      <p>{blog.user?.username}</p>
    </div>}
  </>
  )
}
export default Blog

Here is my backend code that deals with the put request of the "new" like:

blogsRouter.put('/:id', async (request, response) => {
  const body = request.body
  const user = request.user
  console.log(body)

  const blog = {
    user: body.user.id,
    title: body.title,
    author: body.author,
    url: body.url,
    likes: body.likes
  }

  const updatedBlog = await Blog.findByIdAndUpdate(ObjectId(request.params.id), blog, { new: true })
  response.json(updatedBlog)
})

Here is the specific axios handler for put request in another file within frontend directory:

const update = async (id, newObject) => {
  const request = await axios.put(`${ baseUrl }/${id}`, newObject)
  return request
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

State updates are asynchronous in react, because of that when your API call happens:

const handleLike = async (e) => {
    e.preventDefault()

    setBlogLikes(blogLikes + 1)
    
    const response = await blogService.update(blog?.id, updatedBlog)
    console.log(response)

  }

The updatedBlog object still contains old data, not the updated one. So try the following, change your handleLike function to this:

const handleLike = () => {
    setBlogLikes(blogLikes + 1)
}

And add your API call in the useEffect:

useEffect(() => {
    setUpdatedBlog({
      user: blog.user?.id,
      likes: blogLikes,
      author: blog.author,
      title: blog.title,
      url: blog.url
    });
    blogService.update(blog?.id, {
      user: blog.user?.id,
      likes: blogLikes,
      author: blog.author,
      title: blog.title,
      url: blog.url
    }).then((response) => console.log(response));
  }, [blogLikes]);
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