Defining a Reducer Function
Provide an example of a reducer function that takes previous state and an action, and returns a new state based on the action type.
function todosReducer(previousState, action) {
switch (action.type) {
case 'ADD_TODO':
// Return a new state with the new todo added
return [...previousState, action.payload];
case 'TOGGLE_TODO':
// Map through all todos and toggle the completed status of the todo that matches the action's payload id
return previousState.map(todo =>
todo.id === action.payload.id ? { ...todo, completed: !todo.completed } : todo
);
case 'REMOVE_TODO':
// Filter out the todo that needs to be removed (the one that matches the action's payload id)
return previousState.filter(todo => todo.id !== action.payload.id);
default:
// If the action type is not recognized, return the current state unchanged
return previousState;
}
}
This is a reducer function for managing todos in an application state. It handles three action types: 'ADD_TODO' to add a new todo, 'TOGGLE_TODO' to change the completion status of a todo, and 'REMOVE_TODO' to remove a todo. The function returns the new state based on which action is received.