I have the below requirement:
We have a fleet of 10 trucks. Each truck can carry different loads, for our use case the load is medications. A Truck has:
Each Medication has:
And from my assessment, it is best to use a useReducer to achieve the aim. But my challenge is how to construct my state.
const [truck, setTrucks] = useState([
{
sn: "001001",
model: "LightWeight",
weightLimit: "50",
batteryCapacity: 80,
state: "IDLE",
},
{
sn: "001002",
model: "Middleweight",
weightLimit: "150",
batteryCapacity: 30,
state: "IDLE",
},
//rest data here
]);
export const droneReducer = (state, action) => {
switch (action.type) {
case "REGISTER_TRUCK":
return [
...state,
{
sn: action.truck.sn,
model: action.truck.model,
weightLimit: action.truck.weightLimit,
batteryCapacity: action.truck.batteryCapacity,
state: action.truck.state,
},
];
case "LOAD_TRUCK":
case "CHECK_LOADED":
case "CHECK_AVAILABLE":
case "CHECK_BATTERY_LEVEL":
}
};
Thanks
Further to my comments, if you wanted it nested you would add a load property to the Truck object:
export const droneReducer = (state, action) => {
switch (action.type) {
case "REGISTER_TRUCK":
return [
...state,
{
sn: action.truck.sn,
model: action.truck.model,
weightLimit: action.truck.weightLimit,
batteryCapacity: action.truck.batteryCapacity,
state: action.truck.state,
load: action.truck.load
// an array of medicines with qty
},
];
case "LOAD_TRUCK":
case "CHECK_LOADED":
case "CHECK_AVAILABLE":
case "CHECK_BATTERY_LEVEL":
}
};
So it might look like load: [{name: 'COVID vaccine', weight: 2, qty: 9000, code: 'CVD19'}]
And then you would access it like you would access any other property of a truck: truck.load. You can view it's contents, filter it and reset the state with a new value, add stuff to it, remove stuff from it, change the qty of something inside it. Anything.