Reducers for Educational Modules
Demonstrate how to write reducers to update the state based on course progression actions, ensuring immutability and proper state transitions.
const courseReducer = (state, action) => {
switch (action.type) {
// Start a new module
case 'START_MODULE':
return {
...state,
currentModule: action.moduleId,
modules: {
...state.modules,
[action.moduleId]: {
...state.modules[action.moduleId],
started: true,
completed: false
}
}
};
// Mark the current module as completed
case 'COMPLETE_MODULE':
return {
...state,
modules: {
...state.modules,
[action.moduleId]: {
...state.modules[action.moduleId],
completed: true
}
}
};
// Reset the progress of the module
case 'RESET_MODULE':
return {
...state,
modules: {
...state.modules,
[action.moduleId]: {
...state.modules[action.moduleId],
started: false,
completed: false
}
}
};
// Default case to return the current state
default:
return state;
}
};
This code defines a reducer for managing state transitions in an educational course system. It handles actions for starting a module, completing it, and resetting a module's progress. The reducer maintains immutability by returning a new state object each time, using the spread operator to copy the existing state and update only the necessary parts.