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

182
Vistas
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 Respuestas
Responde la pregunta

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