Creating a Reducer for Analytics Data
Provide a code example of a reducer function that handles updating parts of the state related to analytics data when relevant actions are dispatched.
const analyticsReducer = (state = { viewCounts: {}, salesData: [] }, action) => {
switch (action.type) {
case 'INCREMENT_VIEW_COUNT':
const { page } = action.payload;
return {
...state,
viewCounts: {
...state.viewCounts,
[page]: (state.viewCounts[page] || 0) + 1
}
};
case 'SET_SALES_DATA':
const { salesData } = action.payload;
return {
...state,
salesData
};
// handle other actions
default:
return state;
}
};
Reducer for handling analytics data. It responds to two action types: 'INCREMENT_VIEW_COUNT' which increments a view count for a specific page and 'SET_SALES_DATA' which sets the sales data. The state shape consists of 'viewCounts', an object keyed by page names with values being the count, and 'salesData', an array of sales records.