Blog>
Snippets

State Shape Validation on Store Initialization

Demonstrate how to validate the shape and types of the initial Redux store state to prevent runtime type issues when the application starts.
import PropTypes from 'prop-types';

// Define the shape of your initial state using PropTypes
const initialStateShape = {
  user: PropTypes.shape({
    id: PropTypes.number.isRequired,
    name: PropTypes.string.isRequired,
    email: PropTypes.string.isRequired
  }),
  products: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.number.isRequired,
    title: PropTypes.string.isRequired,
    price: PropTypes.number.isRequired
  })).isRequired,
  cart: PropTypes.arrayOf(PropTypes.shape({
    productId: PropTypes.number.isRequired,
    quantity: PropTypes.number.isRequired
  })).isRequired
};

// Your initial state
const initialState = {
  user: { id: 1, name: 'John Doe', email: 'john.doe@example.com' },
  products: [
    { id: 1, title: 'Widget', price: 9.99 },
    // ... other products
  ],
  cart: []
};

// Validate the initial state
PropTypes.checkPropTypes(initialStateShape, initialState, 'prop', 'initialState');
This code imports PropTypes to define and check the shape and types of the initial state of the Redux store. The `initialStateShape` object describes the expected structure and types for the state. The `initialState` object represents the actual initial state data. The `PropTypes.checkPropTypes` method validates if the `initialState` matches the defined `initialStateShape`.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Redux State Shape Validation</title>
</head>
<body>
  <div id="app"></div>
  <!-- Include your bundled scripts below -->
  <script src="path/to/your/bundled/script.js"></script>
</body>
</html>
This is a basic HTML boilerplate to load the JavaScript code. You need to replace `path/to/your/bundled/script.js` with the actual path to your JavaScript file that includes the Redux logic and state shape validation code.