Tengo el siguiente requisito:
Contamos con una flota de 10 camiones . Cada camión puede llevar diferentes cargas, para nuestro caso de uso la carga son medicamentos . Un camión tiene:
Cada medicamento tiene:
Y según mi evaluación, es mejor usar un useReducer para lograr el objetivo. Pero mi desafío es cómo construir mi estado.
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": } };Gracias
Además de mis comentarios, si quisiera que estuviera anidado, agregaría una propiedad de load al objeto Truck :
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": } }; Por lo tanto, podría verse como load: [{name: 'COVID vaccine', weight: 2, qty: 9000, code: 'CVD19'}]
Y luego accedería como accedería a cualquier otra propiedad de un camión: truck.load . Puede ver su contenido, filtrarlo y restablecer el estado con un nuevo valor, agregarle cosas, quitarle cosas, cambiar la cantidad de algo dentro de él. Cualquier cosa.