Perhaps it's just a missing piece of information in my Redux knowledge, but even after seaching for hours, I still have no idea how to create a reusable reducer to update many state properties.
Let's say, I create a simple component MySwitch providing an UI to edit boolean values. There is a related action and a reducer to update the state. I understand how to make it work for a specific property in the state. But how can I create the component (and related reducer) to work with any boolean value from the store, without creating a special reducer for each of them?
Let's say, the state looks like this:
{
items: {
house: { isBig:true, location: ... },
car: { isMine:true, isBroken:false, ... }
},
books: [
{ id:1, available:true, title:... },
{ id:2, available:false, title:... }, ...
]
}
What is the correct mechanism to create various instances of MySwitch to view and edit any given value – like items.house.isBig, items.car.isMine or books[1].available – and update them with the same reducer?
I could inject the property to the component using connect, something like:
ASwitch = connect(state => ({
valueToEdit: state.items.car.isMine
})(MySwitch)
but I have no clue how to pass it to the reducer and how to let it update the respective part of the state. I thought I could provide the path (i.e. "items.car.isMine") to the action:
export const editBoolean = ( path, value ) => {
return {
type: 'BOOL_EDIT',
payload: { path, value }
}
}
and then use something like this in the reducer:
case 'BOOL_EDIT': {
const { path, value } = action.payload;
return {
...state,
[path]: value
}
}
but it doesn't work, seems ES6 doesn't support variable computed properties, a property like state["items.car.isMine"] is created instead.
I have no idea how to go on here. Thanks for any help.