Redux - where to prepare data

I am new to Redux and I have a problem. I have an array of objects in state, after adding a new object to this array I want to change all other objects. For example, something like this:

[{id : 0, visible: false}, {id : 1, visible: true}] - old array [{id : 0, visible: false}, {id : 1, visible : false}, {id : 2, visible : true}] - that I want 

Where should I prepare the old state? As the reduction document said, in the gearboxes I should not do anything with the state, I just need to return a new state. Can I write functions in reducers that will prepare a copy of the previous state and return as a new state? Sort of:

 export function ui(state = initialState, action){ switch (action.type){ case "SOME_ACTION" : var newState = someFunction(state.items, action) return Object.assign({}, state, { items : newState }); default: return state; }} function someFunction(array, action){ .... some code return newArray } 

Or should I keep this feature elsewhere? What are the best able data editing techniques?

+2
source share
1 answer

All state changes must be made in your gearbox. The return of the new state and the change of the old state are the same thing when you do it the same way. That is, the new IS state is data from the old state, possibly changed with the new data.

Given your example, I could do something like:

 function rootReducer(state = initialState, action) { switch(action.type) { case: "SOME_ACTION": var allStateVisibleFalse = state.map(x => Object.assign({}, x, { visible: false} )); return [...allStateVisibleFalse, { id: 2, visible: true}]; } ... } 
+2
source

Source: https://habr.com/ru/post/1246127/


All Articles