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

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

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