How to filter/remove elements from an array within a Store

If I have the following createStore invocation:
export type WeeklyTimesheetSubmission = {
readonly cards: TimesheetCard[];
};

function SomeComponent() {
const [submission, setSubmission] = createStore<WeeklyTimesheetSubmission>({
cards: [],
});
}
export type WeeklyTimesheetSubmission = {
readonly cards: TimesheetCard[];
};

function SomeComponent() {
const [submission, setSubmission] = createStore<WeeklyTimesheetSubmission>({
cards: [],
});
}
What is the proper way to filter/remove an element from that cards list? I have tried the following and I get yelled at by TypeScript saying it's incorrect.
setSubmission("cards", (c) => c.id !== card.id); // Attempt 1: Fail
setSubmission("cards", (c) => c.id !== card.id, undefined!) // Attempt 2: Fail
setSubmission("cards", (c) => c.id !== card.id); // Attempt 1: Fail
setSubmission("cards", (c) => c.id !== card.id, undefined!) // Attempt 2: Fail
Since the cards field is at the top level, is the only option to reference the previous value of the store?
setSubmission((prev) => ({ ...prev, cards: prev.cards.filter((c) => c.id !== card.id) }))
setSubmission((prev) => ({ ...prev, cards: prev.cards.filter((c) => c.id !== card.id) }))
3 Replies
zulu
zulu4w ago
why does
setSubmission("cards", (c) => c.id !== card.id, undefined!)
setSubmission("cards", (c) => c.id !== card.id, undefined!)
fail? but regardless this option might be more desirable
setSubmission((prev) => ({ ...prev, cards: prev.cards.filter((c) => c.id !== card.id) }))
setSubmission((prev) => ({ ...prev, cards: prev.cards.filter((c) => c.id !== card.id) }))
as the one above can leave "holes"
peerreynders
peerreynders4w ago
Even the TodoMVC demo uses filter. The underlying advantage is that even subscribers of just .length (or the array itself) will also rerun.
zulu
zulu4w ago
that is a good points setting to undefined leaves holes and does not change the length this is what the todo app does
removeTodo = (todoId: number) => setState("todos", (t) => t.filter((item) => item.id !== todoId)),
removeTodo = (todoId: number) => setState("todos", (t) => t.filter((item) => item.id !== todoId)),

Did you find this page helpful?