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

400
Views
React: How to update a property of an object?

I want to increase the likes of a single blog by 1 in the incLikes function and put the updated blog back in the blogs state

const App = () => {
  const [ blogs, setBlogs ] = useState(null)

  useEffect(() => {
    blogsService.getAll().then(initialBlogs => {
      setBlogs(initialBlogs)
    })
  }, [])

  const incLikes = blog => {
    ...
  }

  ...

My mongo database contains the following blogs:

[
    {
        "title": "The lost planet in the milky way",
        "author": "Ford Beeblebrox",
        "url": "www.goldenplanet.milky.way",
        "likes": 102,
        "id": "600aabcbf4492017c4068727"
    },
    {
        "title": "How the Vogols destroyed the Earth",
        "author": "Michael Faraday",
        "url": "www.far-far-aday.com",
        "likes": 45,
        "id": "600ab1575883720a04743319"
    }
]
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

To give you a fuller context, here is how you would do it:

  const [blogs, setBlogs] = React.useState(all_blogs);

  const incLikes = (blog) => {
    setBlogs(
      blogs.map((b) => {
        if (b.id === blog.id) b.likes++;

        return b;
      })
    );
  };

  return (
    <div className="App">
      <h1>Blogs:</h1>

      {blogs.map((item, i) => (
        <div key={i}>
          {item.title} (Likes: {item.likes}) --{" "}
          <button onClick={() => incLikes(item)}> Like</button>
        </div>
      ))}
    </div>
  );

So the idea is to pass a blog object into your function, then map through all the blog objects stored in the state and increment the matching one. Here is a sandbox for you.

over 4 years ago · Santiago Trujillo 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!