Actions and Reducers Organization
Illustrate structuring the actions and reducers in an Electron app using Redux, highlighting the concept of action types, action creators, and reducers.
// actions/types.js
// Define action type constants
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
Defines action type constants to avoid hard-coded strings and reduce errors due to typos.
// actions/counterActions.js
import { INCREMENT, DECREMENT } from './types';
// Action creator for incrementing
export const incrementCounter = () => ({
type: INCREMENT
});
// Action creator for decrementing
export const decrementCounter = () => ({
type: DECREMENT
});
Creates action creators for incrementing and decrementing a counter. These functions return action objects that can be dispatched to the store.
// reducers/counterReducer.js
import { INCREMENT, DECREMENT } from '../actions/types';
const initialState = {
count: 0
};
// Reducer function for handling counter actions
export const counterReducer = (state = initialState, action) => {
switch (action.type) {
case INCREMENT:
return {
...state,
count: state.count + 1
};
case DECREMENT:
return {
...state,
count: state.count - 1
};
default:
return state;
}
};
Defines a reducer for the counter. It handles two action types, INCREMENT and DECREMENT, to increase or decrease the count in the state. The reducer returns the new state based on the action received.
// store.js
import { createStore, combineReducers } from 'redux';
import { counterReducer } from './reducers/counterReducer';
// Combine reducers if there are multiple, for now there's only counterReducer
const rootReducer = combineReducers({
counter: counterReducer
});
// Create the Redux store with the combined reducers
const store = createStore(
rootReducer,
// Enable Redux DevTools only if available
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store;
Sets up the Redux store using the createStore function from Redux. Combines multiple reducers using combineReducers, although in this example only counterReducer is present. Connects to Redux DevTools if it's installed in the browser.