I'd like to break down my zustand state into smaller reusable objects; but, the documented zustand patterns all seem to involve promoting operations up to the top-level store object. Is there a way to allow mutations on the inner objects, without necessarily repeating every operation for every object?
By way of example, let's say we have a vehicle object:
function makeVehicle() {
return { going: false };
}
function startVehicle(vehicle) {
return { ...vehicle, going: true };
}
function stopVehicle(vehicle) {
return { ...vehicle, going: false };
}
I can have a state that contains two named vehicles
import { create } from 'zustand';
export default create(set => {
blueVehicle: makeVehicle(),
greenVehicle: makeVehicle()
});
But, it seems like if I want to also export the mutators, I need to repeat each operation, for each object, with a fair bit of boilerplate:
import { create } from 'zustand';
export default create(set => {
blueVehicle: makeVehicle(),
startBlueVehicle: () => set(
state => ({ blueVehicle: startVehicle(state.blueVehicle) })
),
stopBlueVehicle: () => set(
state => ({ blueVehicle: stopVehicle(state.blueVehicle) })
),
greenVehicle: makeVehicle(),
startGreenVehicle: () => set(
state => ({ greenVehicle: startVehicle(state.greenVehicle) })
),
stopGreenVehicle: () => set(
state => ({ greenVehicle: stopVehicle(state.greenVehicle) })
)
});
Is there a simpler way to express this?