Home > database >  MongoDB keeps returning one less value than intended value
MongoDB keeps returning one less value than intended value

Time:06-01

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
}

CodePudding user response:

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]);
  • Related