Blog>
Snippets

Action creators with Object.create(null) payloads

Demonstrate how to construct action payloads with Object.create(null) for improved security in Redux 5.0.1.
const CREATE_ACTION = 'CREATE_ACTION';

// Action creators typically create an object with a type property,
// and a payload that is an object with additional data.
function createAction(data) {
  // Use Object.create(null) to create a payload object with no prototype
  // which avoids issues with objects that have altered prototypes potentially
  // causing security vulnerabilities in your application.
  const payload = Object.create(null);

  // Assign the data passed to the payload's desired properties.
  Object.keys(data).forEach(key => {
    payload[key] = data[key];
  });

  // Return the action object
  return {
    type: CREATE_ACTION,
    payload
  };
}
This code snippet demonstrates how to create a Redux action creator that generates a payload using Object.create(null) to construct an object without a prototype, reducing potential security risks.
/* Reducer function to handle actions */
function myReducer(state = {}, action) {
  switch (action.type) {
    case CREATE_ACTION:
      return {
        ...state,
        ...action.payload
      };
    default:
      return state;
  }
}
This is a reducer function that understands how to handle the action created by the createAction function. It merges the action's payload into the current state, effectively updating the state with new data.
<!-- This is the HTML structure to trigger the demonstrated action. -->
<button id='actionButton'>Create Action</button>
HTML code with a button element. When clicked, it will trigger the action to be dispatched to the Redux store (the script would need additional JavaScript to handle the click event and dispatch the action).
/* CSS to style the button */
#actionButton {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

#actionButton:hover {
  background-color: #45a049;
}
CSS code for styling the button. It provides padding, background color, text color, and changes the background color on hover for a user interaction feedback.
// JavaScript to attach a click event listener to the button

// Assuming a Redux store is available as `store`
document.getElementById('actionButton').addEventListener('click', function() {
  const actionData = { /* ... some data ... */ };
  // Dispatch the action created by the createAction function to the Redux store
  store.dispatch(createAction(actionData));
});
JavaScript code to attach a click event listener to the button with id 'actionButton'. Upon button click, it dispatches the action created by the createAction function to update the Redux store's state with the provided data.