nested push-or-create-array in zustand and immer

Is there an easier way to accomplish this with zustand and immer, ie avoiding the conditional? this is inside a zustand create with immer middleware.
// StateType = { knownPaths: { [key: string]: string[] }; };

addPath(region, location) {
set((state) => {
if (region in state.knownPaths) {
state.knownPaths[region].push(location);
} else {
state.knownPaths[region] = [location];
}
});
},
// StateType = { knownPaths: { [key: string]: string[] }; };

addPath(region, location) {
set((state) => {
if (region in state.knownPaths) {
state.knownPaths[region].push(location);
} else {
state.knownPaths[region] = [location];
}
});
},
9 Replies
haris
haris•3y ago
Do you need any duplicates in this array? If not I think a Map would work really really well here
scatter
scatterOP•3y ago
semantically no, but this has parity with a Json table in my db, which should also never have duplicates but it's not enforced
haris
haris•3y ago
Then yeah, I recommend a Map Would work very well here as you can just do .set iirc, don't have to check if it exists or not to change it
scatter
scatterOP•3y ago
i'm not exactly seeing how a map would help, but something like {knownPaths: {[key: string]: Set<string>}} might
haris
haris•3y ago
Wait is knownPaths an Object or an Array?
scatter
scatterOP•3y ago
an object whose keys map to arrays Map<string, Set<string>> is probably what i want here actually but then idk if immer can drill down into sets which are map values like that
haris
haris•3y ago
Or wait I'm dumb, Map wouldn't work in the way I thought initially Just woke up sorry This does make sense, but I've never used Immer so no clue if the second thing would work
scatter
scatterOP•3y ago
no worries 😄 i'll keep digging, i'm new to immer myself so it feels like i'm just missing something
CaptainStarz
CaptainStarz•3y ago
Logical nullish assignment (??=) - JavaScript | MDN
The logical nullish assignment (x ??= y) operator only assigns if x is nullish (null or undefined).
Want results from more Discord servers?
Add your server