Ensuring Correct Types with Action Creators
Demonstrate creating action creators that enforce the correct payload type to prevent dispatching actions with improper data.
// Define action types
const ActionTypes = {
UPDATE_USER: 'UPDATE_USER'
};
// Action creator with type checking for the 'updateUser' action
function updateUser(payload) {
// Check if payload adheres to the expected structure and types
if (typeof payload === 'object' && payload !== null && typeof payload.id === 'string' && typeof payload.name === 'string') {
// Return the action if payload is correct
return {
type: ActionTypes.UPDATE_USER,
payload
};
} else {
// Throw an error or handle incorrect types accordingly
throw new Error('Payload must be an object with a string id and name');
}
}
// Usage example (will only work if payload is correct)
// const action = updateUser({ id: '123', name: 'John Doe' });
This code snippet demonstrates an action creator function for updating a user, where the payload must be an object containing a string `id` and a `name`. The function checks the type of the payload and its properties before creating and returning the action. If the payload is incorrect, it throws an error.
<!-- HTML structure -->
<div id='app'>
<form id='userForm'>
<input type='text' id='userId' placeholder='User ID' required />
<input type='text' id='userName' placeholder='Name' required />
<button type='submit'>Update User</button>
</form>
</div>
This is the HTML markup defining a simple form with input fields for the user ID and name. When submitted, it will attempt to dispatch an action to update the user, using the provided values.
// JavaScript for the form submission
// Assuming you have already imported or defined 'dispatch'
// Grab form elements
const userForm = document.getElementById('userForm');
const userIdField = document.getElementById('userId');
const userNameField = document.getElementById('userName');
userForm.addEventListener('submit', function(event) {
event.preventDefault();
try {
const action = updateUser({
id: userIdField.value.trim(),
name: userNameField.value.trim()
});
dispatch(action);
} catch (error) {
// Handle the error (e.g., display a message to the user)
console.error(error.message);
}
});
JavaScript that adds a submit event listener to the form. On submit, it fetches values from the input fields, trims them, and attempts to dispatch the updateUser action. If there's an error in creating the action due to incorrect types, it handles the error by logging it to the console.
/* CSS for the form */
#app {
max-width: 300px;
margin: 0 auto;
}
#userForm input[type='text'] {
width: 100%;
padding: 8px;
margin-bottom: 10px;
}
#userForm button {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
#userForm button:hover {
background-color: #45a049;
}
This CSS snippet provides basic styles to the form and its elements. It defines styles for a wrapper with a maximum width, input fields, and a submit button, including a hover state for the button.