S
SolidJS7mo ago
sachaw

Most concise upsert for store?

I'm wondering if there was a more efficient way of doing an upsert operation? This is what I'm doing currently:
const updateNodes = (node: Node) => {
setLocalState(
"nodes",
produce((nodes) => {
const nodeIndex = nodes.findIndex((n) => n.id === node.id);

if (nodeIndex !== -1) {
nodes[nodeIndex] = node;
} else {
nodes.push(node);
}
}),
);
};
const updateNodes = (node: Node) => {
setLocalState(
"nodes",
produce((nodes) => {
const nodeIndex = nodes.findIndex((n) => n.id === node.id);

if (nodeIndex !== -1) {
nodes[nodeIndex] = node;
} else {
nodes.push(node);
}
}),
);
};
2 Replies
sachaw
sachaw7mo ago
I've shrunk it to this:
const updateNodes = (node: Node) => {
const index = localState.nodes.findIndex((n) => n.id === node.id);

setLocalState(
"nodes",
index === -1 ? localState.nodes.length : index,
node,
);
};
const updateNodes = (node: Node) => {
const index = localState.nodes.findIndex((n) => n.id === node.id);

setLocalState(
"nodes",
index === -1 ? localState.nodes.length : index,
node,
);
};
thetarnav
thetarnav7mo ago
i’m upsert that I didn’t know it about upsert before. Keep in mind that the first example will replace node with same id when updating, but in the second the two objects will be merged (merging is probably better)