Reducer behavior - reactjs

As I understand it, when an action is called, all reducers respond. If action exists in the switch case statement of the reducer, it executes. If it doesn't, then the case: default executes which preserves the existing state.
When the action exists in the reducer but the particular property it's trying to update does not exist, it seems to behave OK as there's nothing to update.
For example, I have an action creator that is used to set the visible property of my modals. Each modal has its own Id. My code looks like this:
export default (state = initialState, action) => {
case types.SET_MODAL_IS_VISIBLE:
return Object.assign({}, state,
{ modal22: action.value }
)}
I have the SET_MODAL_IS_VISIBLE in multiple reducers but if modal22 is not defined in a particular reducer, nothing happens and no errors.
Now, I have a scenario that is throwing an error. I have a general purpose date picker component that I built that can be used as a single and independent date picker OR it can be "linked to" another one. The second scenario is useful if I need the user to give me two dates e.g. start and end dates.
I also built a feature where if the date picker is coupled with another one, when the user sets the date in the first date picker, I disable all the dates prior to that date in the second date picker because I don't want the user to unintentionally select an end date that is prior to the start date.
I define my date pickers as below:
const initialState = {
datePickers: {
"startDatePicker": {
activeDate: "8/25/2017",
disabledBefore: "",
linkedTo: "endDatePicker"
},
"endDatePicker": {
activeDate: "",
disabledBefore: "8/25/2017" // This date is set when the user sets the active date in startDatePicker
linkedTo: ""
}
}
}
This scenario is a bit interesting because a state change in one property in my reducer is triggering a state change in another. This is not difficult to do and I have a way of controlling when I do the update.
The action for setting disabled dates looks like below:
...
case types.SET_DISABLED_DATES:
return Object.assign({}, state,
datePickers: Object.assign({}, state.datePickers, {
datePickers[action.datePickerId]: Object.assign({}, state.datePickers[action.datePickerId], {
disabledBefore: action.value
})
})
Please keep in mind that I can and should be able to set disabledBefore even if the date picker is used as an independent one. So, I need my SET_DISABLED_DATES in every reducer.
The problem I'm running into is that whenever I call SET_DISABLED_DATES, I get errors in reducers where the date picker is used as a single/independent one because the date picker Id for its pair is NOT defined in the reducer.
For example, in projectsReducer I may use the date picker as part of a pair so both startDatePicker and endDatePicker are defined and everything works fine.
But I may be using a single instance date picker in the tasksReducer which also responds to the SET_DISABLED_DATES call but it fails because it cannot find the endDatePicker. In this scenario, the tasksReducer is responding to the call I made to set the disabledDates property of endDatePicker in projectsReducer.
I've posted two questions about this already and the only real solution I'm seeing here is that I need to have a condition in my reducer that looks like this:
...
case types.SET_DISABLED_DATES:
if(typeof state.datePickers[action.datePickerId] !== "undefined") { // Making sure that what I'm trying to update exists in the reducer
return Object.assign({}, state,
datePickers: Object.assign({}, state.datePickers, {
datePickers[action.datePickerId]: Object.assign({}, state.datePickers[action.datePickerId], {
disabledBefore: action.value
})
})
} else {
return state;
}
Admittedly, this looks a bit like a kludge but I couldn't really come up with another solution here.
Again, the problem is that for as long as all reducers respond to SET_DISABLED_DATES, it's guaranteed that a particular date picker will not be there and the Object.assign() will throw an error.
Any suggestions? Is the simple condition in the reducer the way to go here? Is it a kludge?
P.S. I tried this code and it works fine and fixes the problem. On the one hand, I feel this is a bit of an anti-pattern but on the other hand, it just seems like a good idea to make sure the property I want to update in my reducer exists before attempting to update it. I'd appreciate your feedback on this. Thanks.

You are just doing basic validation in the reducer before setting the state. That is perfectly fine. I don't think it will be a good practice to check the store in the action creator to prevent dispatching actions on objects not in the store (how would you do that anyway!).
What I don't understand is, how can a datepicker be linked to another datepicker that isn't in the store? Maybe dispatch a create and teardown action on the component's didMount and willUnmount?
I don't know your full requirements but I think we can make it a lot simpler. I'd do something like this:
The store:
{
datePickers: {
id1: {
value: '',
minValue: '',
maxValue: '',
},
id2: {
value: '',
minValue: '',
maxValue: '',
}
}
}
Now, unless you are making some kind of coupled datepicker components that will always behave in pairs, I believe the cleanest approach would be to set the disabled value in the linked datepicker in the mapDispactchToProps function in your parent component.
That is where you would set ids to the components, and you know exactly which component should be disabled before another.
Something like:
dispatch => ({
setArrivalDate(value) {
dispatch(datePickerActions.setValue(arrivalDateId, value);
dispatch(datePickerActions.setMaxValue(depatureDateId, value);
},
setDepatureDate(value) {
dispatch(datePickerActions.setValue(depatureDateId, value);
dispatch(datePickerActions.setMinValue(arrivalDateId, value);
}
})
This may not be abstract enough, but is clean.
You could do the same thing if you have a paired component, but you'd still need to know which date comes before another. It'd be a hassle to make a generic abstraction around it.

Remove the bold part in your code below
...
case types.SET_DISABLED_DATES:
if(typeof state.datePickers[action.datePickerId] !== "undefined") { // Making sure that what I'm trying to update exists in the reducer
return Object.assign({}, state,
datePickers: Object.assign({}, state.datePickers, {
datePickers[action.datePickerId]: Object.assign({}, state.datePickers[action.datePickerId], {
disabledBefore: action.value
})
})
} else {
return state;
}
Also, a little bit of es6 spread and a helper switchcase function makes this code much more readable.
const newReducer = (state = defaultState, action) => switchcase({
[types.SET_DISABLED_DATES]:
state.datePickers[action.datePickerId] === undefined
? state
: ({ ...state,
datePickers: { ...state.datePickers,
[action.datePickerId]: { ...state.datePickers[action.datePickerId],
disabledBefore: action.value,
},
},
}),
})(state)(action.type);
Using lodash/fp/set, the code becomes
const reducerWithLodash = (state = defaultState, action) =>
switchcase({
[types.SET_DISABLED_DATES]:
state.datePickers[action.datePickerId] === undefined
? state
: set({...state}, `datePickers.${action.datePickerId}.disabledBefore`, action.value)
})(state)(action.type)
I haven't tested the lodash version, so please take that with a grain of salt (Dan Abramov seems to approve)

Related

Change another key's value using react-redux In React Native Expo

First, I am not good at English. I'm sorry.
I am creating a daily and weekly quest check app for a game, and in this app, Users can check daily quests for each character after registering the user's character. However, if I check one character's daily quest, all other characters are checked. This phenomenon continues after :
Creating a character until the app's restart and
Pressing the app's full initialization button until the app's restart
I tried for more than a week. And I found out that this appears in the reducer of redux(react-redux). However, I couldn't understand it at all with my skills, so I posted a question.
First, images is:
my imgur
And I thought you wouldn't understand it through pictures, so I prepared a
YouTube link
.
This is
how the checkbox arrangement of the two characters actually changes in the redox devtool.
I'm sorry that I haven't inserted the image yet.
const initialState = {
LoaData: {},
weekADay: '',
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'CHECKBOX_REDUX':
return changeCheckbox(state, action);
default:
return state;
};
The above code is the reducer of react-redux.
And the change Checkbox (state, action) function is as follows.
const changeCheckbox = (state, action) => {
let {
contentType, // in this question, i use 'daily' only
firstIndex, // this used dividing content
id, // this is character's unique id(=new Date) and checked character
value // i send checkbox array ex) [false, false, false].
} = action.payload;
let newState = Object.assign({}, state);
let character = newState.LoaData.characters[id];
let filteredContents = character.contents[contentType];
if(contentType === 'daily') { // for test, show only 'daily'
let weekADay = newState.weekADay; // Mon or Tue or Wed ...
for(let i = 0; i < filteredContents[weekADay][firstIndex].value.length; i++) {
filteredContents[weekADay][firstIndex].value[i] = value[i];
}
}
return newState;
}
And the bottom is console.log(action.payload)
{
"contentType": "daily",
"firstIndex": 0,
"id": "1632050917445",
"value": [ true, false, false ],
}
Through many tests, it has been found that a problem occurs in the for statement. I also confirmed that the desired character's nickname changes normally. However, in the for statement, it was confirmed that the boolean of the same index of 'the different character's value' was also changed for each iteration.
please help me
redux: 4.1.1
react-redux: 7.2.4
react: 16.13.1
expo: 42.0.1
It depends on how you creating and updating your characters in the rest of the store, but you might be sharing references for the characters objects between each other. You are mutating the store which you are not supposed to do in redux.
You call object.assign on the old state, and create newState. However, that only creates a new object for new state itself. All of its properties are still referring to the same objects as the old state.
Same with your assignments - let character = newState.LoaData.characters[id]; isn’t actually creating a new object at any point. You need to use object.assign for that, all the way down to the property you are changing, or use the spread operator.

one action updates multiple reducers performance issue

In the current app I have set up multiple redux reducers to store data. Lets just call them 'user-reducers' and 'pet-reducers'. The 2 are very similar, they both have a posts[]. Now whenever user likes a post inside posts[], an action 'likeDone' is fired. Now I have 2 choices of implementing the redux update:
Option 1: both 'user-reducers' and 'pet-reducers' listens to 'likeDone'. IMO, this is inefficient in the later stages when I have more similar reducers and all of them listing to one action.
Option 2: change 'likeDone' into 2 more explicit actions ex. 'likeUserPostDone' 'likePetPostDone' and each reducer reacts to the matched action. This way, reducer updates seem more efficient but there will be more action types later on which will end up with lots of 'switch - case' and I'm not sure if that is a good practice.
Thanks for reading and please tell me what's the best for my case.
Have both reducers listen to your action if they both change when that action occurs. All redux reducers efficiently listen to all dispatched actions. They ignore actions if it doesn't change state.
const petPostReducer = (prev = defaultValue, action = {}) => {
const { type, payload} = action;
switch (type) {
case "LIKE_DONE": {
const {id} = payload || {};
const oldItem = prev[id] || {}
const newItem = {...oldItem, like: true}
return {
...prev
[id]: {...updateItem, [id]: newItem};
}
default: {
return prev; // Ignore all other actions != LIKE_DONE
}
}
};
It is fine to create more explicit actions, but you usually want to do so when you have different actions. (There are always exceptions)
When possible, avoid logic in your reducers.
If pets and user data are very similar, consider changing your state shape and use one reducer posts.
console.log(state.posts) =>
{
0: {type: 'user' like: false},
1: {type: 'pet' like: false},
2: {type: 'user' like: true},
}
Please avoid premature optimization. I often do things that are less efficient in favor of simple, concise, immutable, readable and useful code. If you are targeting a feature phone or find a real performance bottleneck, you will need to measure with performance monitoring tools. The JavaScript engine optimizations are continuously improving and results are often surprising.

How to make several fields editable in React and Redux?

I have an object in my redux state
const obj = {
name: 'name',
age: 2,
place: 0,
}
I show these values on the page but I want to make two of them editable so that the object can be updated.
For that I'm basically getting values from two inputs and sending them to my action
export const saveEditedData = data => dispatch => {
dispatch({
type: CHANGE_DATA,
data,
});
}
and then in reducer
case 'CHANGE_DATA':
return {
...state,
obj: {
...state.obj,
name: action.data.name,
age: action.data.age,
}
}
The problem that I'm facing is that if one value is updated and another is not then after this action my second value in empty.
My question is what is a good way to determine which field is changed and update only it?
So far I only came up with putting if else in action to dispatch certain thing. Maybe there is a better way?
You can 1. make each field update with individual actions, changeName, changeAge, etc, or 2. filter the action payload to get rid of the unwanted values before putting them in your obj:
case 'CHANGE_DATA':
return {
...state,
obj: {
...state.obj,
...action.data.filter(el => !!el)
}
}
(the !! notation is converting the array elements to booleans when filtering, not strictly necessary but sanitary)
EDIT: Sorry I misunderstood your data shape, see comments.

Better syntax to update nested objects on redux

Given a reducer example like the following
_({
expandAbility: (state, a: { which: string }) => ({
...state,
report: state.report && {
waitingForIt: false,
content: state.report.content && {
...state.report.content,
interaction: {
expandAbilities: !state.report.content.interaction.expandAbilities.contains(a.which)
? state.report.content.interaction.expandAbilities.add(a.which)
: state.report.content.interaction.expandAbilities.remove(a.which)
}
}
}
}),
})
(state type given below just for question context purposes)
const initialState = {
report: undefined as
| {
waitingForIt?: boolean
content?: {
supportedFightIds: number[]
deathCut: number
reportInfo: any
deathsFull: any
deathsByPlayer: any
deathsByAbility: any
interaction: {
expandAbilities: Set<string>
}
}
}
| undefined,
error: undefined as Error | undefined
}
Is there any kind of trick or "flavor-of-the-moment" library which would allow me to write a reducer update operation like expandAbility in a shorter way? (besides maybe creating some vars to reference inner paths)
There are lots of immutable update utilities out there, check out some options at https://github.com/markerikson/redux-ecosystem-links/blob/master/immutable-data.md#immutable-update-utilities and see what would be the best fit for you.
For starters check out Immutability-helper or immer.
So there are two things you could do to help simplify this. The first thing I like to do is move the logic out of the reducer and instead just pass in a value and say set expandAbilities to action. expandAbilities.
The second is actually something we do at work. We use immutableJS and wrote a single reducer that handles all of our state calls because you can give it a path of the parts of state that need to be updated and the value to update it with so we extracted that out and now it is easy to say dispatch(actions.update({path: ['report', 'content', 'interaction', 'expandAbilities'], value: '123' }))
You can even expand this so you can pass in a list of values that need to be updated and even preform validations around the data.

redux state updating incorrectly

I was trying to study the redux flow with an example. But got stuck upon in between. Here is the plunkr link for the same.
function combineReducers(currentState, action) {
var nextState = Object.assign({}, currentState);
/*On load placeholder details for all thumbnails*/
var placeholder = {
urlPath: "http://placehold.it/640x480",
header: "PLACEHOLDER",
description: "Description text for the above image"
};
if (currentState === undefined) {
nextState = placeholder;
return nextState;
}
//Problem here i guess
nextState = {
animals : animalReducer(nextState.animals, action),
architecture : architectureReducer(nextState.architecture, action)
}
return nextState;
}
The application loads with an initial state of setting all media elements to a placeholder. ( That is working )
On individual button click, it was supposed to fetch details of each category and only populate those media element.
Problem:
When i click the Go button, both 1 and 2 elements is updating
together. Ideally i was expecting to get only Animal details on
clicking element 1, Architecture details on element 2, Nature on 3 and
People on 4.
I have not implemented 3 and 4 as i am sure if this works, then it will be more of just adding additional actions and reducers for each piece of state.
I think the problem lies in, rootReducer.js line 19, or index.js, Line 34 or 37, but not sure how to proceed! Any pointers will be of great help! Ive already pulled off a hell lot of hairs on my head today!
PS: I know doing in jquery is kind of crud, but just for learning purpose.!
Advanced thanks for the helpers!
Cheers.
https://plnkr.co/edit/WDyQHy5tftm2EX6AFQ9j?p=preview
var defaultState = {
animals: Object.assign({}, placeholder),
architecture: Object.assign({}, placeholder)
};
if (currentState === undefined) {
nextState = defaultState;
return nextState;
}
nextState = {
animals : animalReducer(nextState.animals, action),
architecture : architectureReducer(nextState.architecture, action)
}
The reducers were not returning the original state in the default case
Default state format and the combined reducer state format were different
In both animalReducer and architectureReducer you need to return currentState in the default: case, otherwise you'd null the other part each time something changes. nextState is not defined in default:.
A reducer by default does not do anything to the state, it has to keep it unchanged. Only if there is a matching action, it should create a new object with the updated state. The thing here is that you do not adher to that rule and by chance null the state by default.

Resources