Blog>
Snippets

Utilizing Action Creators for Type Consistency

Demonstrate how to use action creators to encapsulate the logic for creating actions, especially when the type might change due to application updates, to maintain consistency across the application.
// Define Action Types
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';

// Action Creators
function incrementValue() {
    return { type: INCREMENT };
}

function decrementValue() {
    return { type: DECREMENT };
}

// Usage in a Component or Middleware
// dispatch(incrementValue());
// dispatch(decrementValue());
This JavaScript code defines action types and corresponding action creators. The action creators encapsulate the logic for creating actions, thus ensuring type consistency across the application. When dispatching actions, you call the action creators rather than typing out the action object directly, which reduces the chance of errors and makes updating action types easier.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Action Creator Demo</title>
<script src="path_to_your_redux_store_and_action_creators.js"></script>
</head>
<body>
<button id="incrementBtn">Increment</button>
<button id="decrementBtn">Decrement</button>
<script>
    // Assuming you've set up a Redux store and included it here
    document.getElementById('incrementBtn').addEventListener('click', function() {
        store.dispatch(incrementValue());
    });

    document.getElementById('decrementBtn').addEventListener('click', function() {
        store.dispatch(decrementValue());
    });
</script>
</body>
</html>
This HTML snippet creates a simple webpage with two buttons to increment and decrement a value in a Redux store. Each button has an event listener that dispatches the appropriate action by invoking the action creators defined earlier.
button {
    margin: 5px;
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
}
button:hover {
    background-color: #f0f0f0;
}
This CSS provides basic styling for the buttons on the webpage, including a hover effect to improve user interaction by providing visual feedback when the mouse cursor is over the buttons.