Reputation: 795
A lot of answered question about how to change a single value, but I still can't figure it out how to change only type
value only for Mac and keep other values intact.
const initialStateMac = {
type: MacBook,
os: MacOS
};
const initialStatePc = {
type: Laptop,
os: Windows
};
const rootReducer = combineReducers({
mac: macReducers,
pc: pcReducers
});
const store = createStore(rootReducer);
export const Mac = (state = initialStateMac, action) => {
switch (action.type) {
case "SET_DEVICE_TYPE":
return {
...state,
type: action.payload
};
default:
return state;
}
};
export const Pc = (state = initialStatePc, action) => {
switch (action.type) {
case "SET_DEVICE_TYPE":
return {
...state,
type: action.payload
};
default:
return state;
}
};
{
type: "SET_DEVICE_TYPE",
payload: "ddd"
}
to be clear, I want get:
Mac: {
type: ddd,
os: MacOS
},
Pc: {
type: Laptop,
os: Windows
}
but not:
Mac: {
type: ddd,
os: MacOS
},
Pc: {
type: ddd,
os: Windows
}
Upvotes: 0
Views: 43
Reputation: 811
In case with multiple reducers just using different action types for every reducer correspondingly would be the easiest solution
The answer below was given with the assumption that 1 reducer was used with initalState {Mac: {type: "", os: ""}, PC: {type: "", os:""}}
If you want to specifically change type attribute of the object with "Mac" key You could use this.
export default (state = intialState, action) => {
switch (action.type) {
case "SET_DEVICE_TYPE":
const {Mac} = state;
return {
...state,
Mac: {
...Mac,
type: action.payload
}
};
default:
return state;
}
};
Note: If you want to specifically change type attribute of the object with "Mac" key, then would be better if the action type was like "SET_MAC_DEVICE_TYPE"
Also if the key need to be dynamic -
// action.payload = {key: "Mac", type: "ddd"}
export default (state = intialState, action) => {
switch (action.type) {
case "SET_DEVICE_TYPE":
const initValue = state[action.payload.key];
return {
...state,
[action.payload.key]: {
...initValue,
type: action.payload.type
}
};
default:
return state;
}
};
Upvotes: 1
Reputation: 841
Pass initialState.Mac into the reducer as the default state
export default (state = initialState.Mac, action) => {
switch (action.type) {
case "SET_DEVICE_TYPE":
return {
...state,
type: action.payload
};
default:
return state;
}
};
Upvotes: 0