简体   繁体   中英

Redux initial state for variable reducer

In my program I have multiple grids, but they are very similar, so iIdecided to make one reducer for all of them to keep my code nice and DRY. When I dispatch event to change store I send grid name as argument along with payoload and everything writes to store under that grid name.

For example: If I send event to change grid header of catalog grid then store will look like this: (Lets persume users was already in store)

grid: {
    catalog: {
        headers: {
            some data
        }
    },
    users: {
        headers: {
            some other data
        }
    }
}

My question is how do I write modular initial state? Currently I have no initial state except grid names, because without them my code doesn't work. When I need to set something as initial, then I have to include it in my function initializeGrid which dispatches some events to set something similar to initial state.

But without initial state my reducer is pretty messy, because in almost every case i have to check if there is some state or if this is first entry.

Just know that i am not lazy but my initial state would be like 300 rows long and it would not be DRY :/

What is correct solution?

Why do you need an initial state other then {} ?

The reducer can just update the state with the required value. If the key exists, its value is updated, if it doesn't exist, it will be added. Take a look at the following example:

let x = { "a" : { "b": 11 }}
let y = { ...x, "c" : { "d": 22 }}
let z = { ...y, "a": { "b": 33 }}

values are as following (omitted the "" for easier reading):

x: { a: { b: 11 }
y: { a: { b: 11 }, c: { d: 22 }}
z: { a: { b: 33 }, c: { d: 22 }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM