Using nested store #85
-
What's the best / recommended way of using the stan-js with nested states? Let's say for example I'm building a habit tracker. export const {actions} = createStore({
entries: {
'2024': {
'2024-10-29': {
value: 10,
details: 'Had a great run'
}
}
),
});
// I only tried updating it in an immutable way
// method A
actions.setEntries(prev => ({
...prev,
'2024': {
...prev['2024'],
'2024-10-30': {
value: 0,
details: "Couldn't run because I had to debug stan-js"
}
}
}))
// method B
actions.setEntries(prev => {
prev['2024']['2024-10-31'] = {
value: 0,
details: "Still debugging"
};
return prev;
}) I haven't tried for arrays yet, but I liked zustand for his immer plugin. Do you have any plans to integrate it? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hello @gabimoncha! 😊 Thank you for starting this interesting topic!
type EntryPayload = {
value: number
details: string
}
const { useStore, actions } = createStore({
entries: {
'2024': {
'2024-10-29': {
value: 10,
details: 'Had a great run',
},
},
} as Record<string, Record<string, EntryPayload>>,
})
const updateEntry = (year: string, date: string, payload: EntryPayload) => {
actions.setEntries(produce(draft => {
draft[year][date] = payload
}))
}
// Happy coding! 🚀 I hope this helps! Let me know if you have any more questions or thoughts. 🌟 |
Beta Was this translation helpful? Give feedback.
Hello @gabimoncha! 😊 Thank you for starting this interesting topic!
immer
is a pure JavaScript library, so feel free to use it withstan-js
, since "integration" is already here 😅. Here's some example code to illustrate: