Blog>
Snippets

State Shape Normalization

Explain how to design the initial state and transform incoming data to adhere to a consistent state shape, preventing type issues.
<div id="app"></div>
HTML structure to mount our data normalization example.
/* CSS styles for the example, assuming a div with id 'app' */
#app {
    font-family: Arial, sans-serif;
}
Basic CSS to style the 'app' container.
// Define the initial state shape
const initialState = {
    id: null,
    name: '',
    properties: {},
    tags: []
};

// Function to normalize incoming data to the initial state shape
function normalizeData(incomingData) {
    return {
        id: typeof incomingData.id === 'number' ? incomingData.id : initialState.id,
        name: typeof incomingData.name === 'string' ? incomingData.name : initialState.name,
        properties: typeof incomingData.properties === 'object' ? incomingData.properties : initialState.properties,
        tags: Array.isArray(incomingData.tags) ? incomingData.tags : initialState.tags
    };
}
JavaScript function to normalize incoming data to match the pre-defined shape of the state, handling different data types appropriately.