Redux store having multiple 'version' of states under reducer names - redux

I was trying to have separated reducer files for each container file I have, resulting in different reducer exports for each container and I combine it with combineReducers.
I want my store to have state that structured like so:
state = {
currentFilter: 'all',
todos: [],
displayed: [],
}
But instead get a structure like this:
state = {
addReducer: {
currentFilter: 'all',
todos: [],
displayed: [],
},
displayReducer: {
currentFilter: 'all',
todos: [],
displayed: [],
},
filterReducer: {
currentFilter: 'all',
todos: [],
displayed: [],
}
}
the way I create the store:
const store = createStore(
combineReducers({addReducer, displayReducer, filterReducer}),
applyMiddleware(thunk, logger)
);
The problem is when an action got dispatched, the state 'slice' that got updated is only the part associated with the reducer handling that action (in this case below, only the slice on addReducer got updated.
The way I write my reducers is only exporting 1 reduce function for each reducer file.
Is there any workaround to handle this, or a better and more correct way to deal with multiple reducers, so that the 'single source of truth' concept really happens on my Redux store(instead of different source for different reducer)? Thanks!
EDIT: one of my reducers(the other two are very similar to this one, accepting only 1 switch case and a default case)
export default function reduce(state = initialState, action) {
switch (action.type) {
case types.ADD_TODO:
let newTodos = [...state.todos, action.data.todo];
let newDisplayed = [...state.displayed];
if (state.currentFilter !== 'completed') {
newDisplayed.push(action.data.todo);
}
console.log(Object.assign(
{},
state,
{
todos: newTodos,
displayed: newDisplayed,
}
));
console.log('newTodos:', action.data.todo);
return Object.assign(
{},
state,
{
todos: newTodos,
displayed: newDisplayed,
}
);
default:
return state;
}
};

I think you are confusing things, you should only have one reducer not three (in your scenario). You should create different reducers to manage different portions of the state, you shouldn't create different reducers about the same portion of the state just addressing different functionalities. You have action creators for it.
You are breaking the "single source of truth" principle from the beginning. So my suggestion is to have one reducer only in your case.
See the docs for more about this with good examples. LINK
Just the naming suggests confusion, you should have a todoReducer which is associated with the todo resource in your app. The addReducer is associated with a type of action same for the other two, which is not what you want to do.
I hope this clarifies things a bit but when in doubt check the redux docs they are pretty great!

Related

Updating normalised data without causing more re-renders outside of the state slice that has been updated

I have some normalised data (items) within my redux store:
{
items: {
index: ['a','b'],
dict: {
a: {
title: "red",
},
b: {
title: "car",
}
}
},
...
}
So, if I want to update anything within an item object, the reducer looks like this:
...
const itemsReducer = (state = initialState.items, action) => {
switch (action.type) {
case itemsActions.types.UPDATE_ITEM: {
return {
...state,
[action.payload.itemId]: {
title: action.payload.title,
}
}
}
default: return state;
}
};
But this technique creates a new object for items, which can cause unnecessary components to re-render, when really it should only cause components that subscribe to state changes of the individual object to re-render.
Is there any way to get around this?
That is how immutable updates are required to work - you must create copies of every level of nesting that needs to be updated.
In general, components should extract the smallest amount of data that they need from the store, to help minimize the chance of unnecessary re-renders. For example, most of the time a component probably shouldn't be reading the entire state.items slice.
FWIW, it looks like you're hand-writing your reducer logic. You should be using our official Redux Toolkit package to write your Redux logic in general. RTK also specifically has a createEntityAdapter API that will do most typical normalized state updates for you, so you don't have to write reducer logic by hand.
I'll also note that the recently released Reselect 4.1 version has new options you can use for customizing memoized selectors as well.

Is it possible to reassign the whole state in a slice reducer (using Redux ToolKit)?

I am using Redux Toolkit's createSlice().
And trying to create a reducer that populates data from an external source into the redux state.
I'm trying to update the whole state by passing in an object in the action payload:
.
reducers: {
populateData: (state, action) => {
state = action.payload
}
.
but it will only work if I create a reducer for each object key.
Is there a way to do this all at once?
This is a common misunderstanding, and I actually just wrote a new "Writing Reducers with Immer" docs page yesterday that answers this question. Quoting that:
A common mistake is to try assigning state = someValue directly. This will not work! This only points the local state variable to a different reference. That is neither mutating the existing state object/array in memory, nor returning an entirely new value, so Immer does not make any actual changes.
Instead, you want: return action.payload, which will replace the existing state entirely.
I ran in to this problem
This does not work
reducers: {
setSession: (state, action: PayloadAction<SessionState>) =>
state = action.payload,
},
This does work
reducers: {
setSession: (state, action: PayloadAction<SessionState>) =>
action.payload,
},

React Redux accessing dynamically filtered state in mapStateToProps - rerendering woes

I have a functional component, that is passed instructions on what to pull from the redux store.
Using mapStateToProps=(state, ownProps), I can happily pull the required items from state (store) - but, at a cost of any changes in the entire state tree triggering rerunning mapStateToProps and a gazillion rerenders.
Let me unpack.
Here's a snapshot of part of the store:
{
settings: {...stuff...},
projects: [...stuff...],
definitions: [...stuff...],
themes: [...stuff...],
surfaces: {
'6': { <--- VARIABLE PASSED TO COMPONENT
surface: {
STRIP: [..stuff..],
GLOBAL: { <--- CATEGORY PASSED TO COMPONENT
DISPLAY: {...stuff...},
ASSIGNMENT: { <--- LIST OF REQUIRED OBJECTS HAS
A_TRACK: { SUBCATEGORY AND TARGET (A_TRACK etc...)
value: 0,
type: 'switch',
label: 'TRACK'
},
A_SEND: { <--- ANOTHER OBJECT I NEED TO GET
value: 0,
type: 'switch',
label: 'SEND'
},
A_PAN: {
value: 0,
type: 'switch',
label: 'PAN'
},
},
FADER_BANKS: {...stuff...},
STATUS: {...stuff...},
LOTS_MORE_STUFF
My parent component passes the required instructions to the child.
<RefMixerGroup
portId = {this.props.portId}
items={[
{parent: 'GLOBAL', group: "ASSIGNMENT", target: "A_TRACK"},
{parent: 'GLOBAL', group: "ASSIGNMENT", target: "A_SEND"},
]
}
/>
mapStateToProps is pretty simple:
const mapStateToPropy = (state, ownProps) => {
return {
groupItems: getItemsFromState(state.surfaces[ownProps.portId].surface, ownProps.items)
}
}
and the work is done in a simple function:
const getItemsFromState = (subState, items)=>{
let groupItems=[]
for (let i = 0; i < items.length; i++) {
const item = items[i];
const base = subState[item.parent];
let groupItem = base[item.group][item.target]
groupItems.push({...groupItem, target: item.target})
}
return groupItems
}
But because I am creating this array of matches, I think redux thinks I should be subscribing to every item in the tree...when I only want changes on the found elements, in this case:
surfaces[6].surface[GLOBAL][ASSIGNMENT][A_TRACK]
surfaces[6].surface[GLOBAL][ASSIGNMENT][A_SEND]
I tried using reselect and the rereselect instead of my getItemsFromState function above,
but all with the same result. Any change in that tree, starting with surfaces[6] triggers mapsStateToProps and a rerender.
There must be way around this, but I can't figure it out. I tried using areStatesEqual but it only provides nextState and prevState, and I need ownProps to compute equality. I possibly could use areStatePropsEqual, but that only works AFTER recomputing mapStateToProps unnecessarily.
There must be a way!
getItemsFromState is creating a new groupItems array reference every time it runs. It will be called after every dispatched action. Since connect re-renders any time any of the fields returned by mapState have changed to a new reference, your code is forcing React-Redux to re-render every time.
This is specifically why you should use memoized selectors to only return new derived data references if the input references have changed, typically with Reselect's createSelector. If your use of Reselect isn't helping here, it's likely that your selectors aren't being set up correctly, but I'd need to see specific examples to give advice there.
It's also why components should subscribe to the smallest amount of data that they actually need.
If you are using a function component, I'd suggest using useSelector instead of connect as well.

How to work with Redux reducers and server API

What is a better way to create reducers with handleActions in redux-actions:
1. Create reducers for each CRUD operations (like add data, delete data) and combine it. How set initialState in this case?
2. Set actions in one reducer (fetchDeleteDataRequest, fetchDeleteDataSuccess, fetchAddDataRequest, fetchAddDataSuccess by example)?
You can have sperate reducers and or common reducers to add or delete data that is up to you. If you are considering separate actions for add and delete you will need to keep the data consistent. But having a common function to deal with the CRUD operations is ideal since this will reduce the amount of code that you have to use but you will need a way to distinguish them as well (maybe bypassing some variable ADD or DELETE). let's consider and list of items that you will be adding or deleting. This list can be an empty array in the beginning (initialState) and pass it as props to your component.
Actions
export const addDeleteItem = data => dispatch => {
// you can perform REST calls here
dispatch({
type: ADD_REMOVE_DATA,
payload: data
});
};
Reducers
let initialState = {
items:[]
}
export default (state = initialState, action) => {
switch (action.type) {
case ADD_REMOVE_DATA:
if(action.payload.event === 'ADD'){
return {...state,items:[...state.items,action.payload.item]}
}else if(action.payload.event === 'DELETE'){
return {...state,items:state.items.filter(item=>item.id !== action.payload.item.id)}
}else if (action.payload.event === 'UPDATE'){
//handle your update code
}
}
}
This is just an example you can follow something like this to avoid code duplication.

How do I define a reducer at the top level?

I have two reducer files that handle the two areas of state in my module...
export interface MyState {
people: PeopleState;
pets: PetState;
}
export const reducers: ActionReducerMap<MyState> = {
people: peopleReducer,
pets: petsReducer
};
This works fine. However, I have some actions that need to update both areas of the state. I'd like to handle this by having a reducer file that deals with things at the MyState level and can update people and pets. I'd like to keep both the existing reducers that handle this at the lower levels.
I can't see how to register the top level reducer. The way the code is now, any reducer added to the ActionReducerMap must be added as a property inside MyState rather than handling MyState as a whole.
Anyone got any ideas?
Thanks
Nick
I guess that the only solution here is to use metaReducer, check this article: https://netbasal.com/implementing-a-meta-reducer-in-ngrx-store-4379d7e1020a
Description: metaReducer is a kind of reducer that stays above other reducers. It should have it's own actions, can have it's own effects. You can use it in such way:
export function metaReducer( reducer ) {
return function reduce( state: ParentState, action: MetaReducerAction ) {
switch(action.type)
case PARENT_ACTION:
return {
...state,
people: peopleReducer(state.people, new DoSthWithPeople()),
pets: petsReducer(state.pets, new DoSthWithPets())
}
default:
return reducer(state, action);
}
}
Where:
interface ParentState {
pets: PetsState,
people: PeopleState
}
type MetaReducerAction = ParentAction <-- this has type PARENT_ACTION
So the workflow is straight forward. In a place that you want a action to update both people and pets states, you need to dispatch PARENT_ACTION, then the actions DoSthWith... are going to be triggered on both slices of state. If you dispatch different action (the action of type that is not handled by the metaReducer, so sth different to PARENT_ACTION) then it will allow other reducers to handle the action (check whats in default section).
The last part is configuration, it should look like this:
StoreModule.forFeature(compose(metaReducer, combineReducers)(reducers))
Where reducers is just:
const reducers = {
pets: petsReducer,
people: peopleReducer
}
Edit: formatting

Resources