Reputation: 132
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?
Upvotes: 0
Views: 933
Reputation: 1181
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.
Upvotes: 4