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

181
Visualizações
Is there a shorter way to update a svelte store?

I have a svelte store that uses this data:

{ "books": [
   {
      "id": "F0tE_25",
      "title": "Abc",
       ...
   },
      "id": "zNPAQit",
      "title": "Ny, Ny",
       ...
   }
 ]
}

I edit a book in a form and call the function below to update the store (id is the book id to update and bookData is the updated data (from the form):

updateBook: (id, bookData) => {
   bookstore.update(items => {
   const index = items.findIndex(i => i.id ===id)
   const updatedBook = {...items[index], ...bookData}
   const updatedBooks = [...items]
   updatedBooks[index] = updatedBook
   return updatedBooks
})
}

It works. It just seems like a lot of juggling to perform an update. Wondered if there was a better way?

almost 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

There are a few problems associated with the approach in the question viz use of findIndex. If the item with the given id doesn't exist the value of index will be -1 which will result items[index] to be undefined and will be the cause of other undesired behavior.

You can use .map() to eliminate and simplify the update. Here is an example.

updateBook: (id, bookData) => {
  bookstore.update(items =>
    items.map(item => {
      if (item.id === id) {
        return { ...item, ...bookData };
      }
      return item;
    })
  );
}

Edited: @pilchard's answer might be even clearer implementation with the use of ternary operator.

updateBook: (id, bookData) => {
  bookstore.update(items =>
    items.map(item => {
      return item.id === id ? { ...item, ...bookData } : item;
    })
  );
}

Hope that helps.

almost 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