Blog>
Snippets

State normalization with createEntityAdapter

Use the createEntityAdapter to normalize server response data for efficient state updates and retrievals.
import { createEntityAdapter, createSlice } from '@reduxjs/toolkit';

// Define an entity adapter for the 'user' entity
const usersAdapter = createEntityAdapter();

// Define an initial state using the adapter's getInitialState method
const initialState = usersAdapter.getInitialState();

// Create a slice that represents the 'users' state
const usersSlice = createSlice({
  name: 'users',
  initialState,
  reducers: {
    // Use the adapter's generated reducer functions for adding and updating
    usersReceived(state, action) {
      usersAdapter.setAll(state, action.payload);
    },
    userAdded: usersAdapter.addOne,
    userUpdated: usersAdapter.updateOne,
  },
});

// Export the reducer and the generated selectors
export const { usersReceived, userAdded, userUpdated } = usersSlice.actions;
export default usersSlice.reducer;
export const {
  selectAll: selectAllUsers,
  selectById: selectUserById,
  selectIds: selectUserIds,
} = usersAdapter.getSelectors(state => state.users);
This JavaScript code defines a 'users' entity using the `createEntityAdapter` from Redux Toolkit. We define a `usersAdapter` with default configuration, an `initialState` generated by `getInitialState`, and a `usersSlice` which contains the reducer logic. `usersSlice` actions are exported for usage in the application, as well as selectors generated by `usersAdapter.getSelectors` for selecting data from the state.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>State Normalization Example</title>
  <script src="https://cdn.jsdelivr.net/npm/redux@4.0.5/dist/redux.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@reduxjs/toolkit@1.5.0/dist/redux-toolkit.umd.min.js"></script>
</head>
<body>
  <!-- The rest of your HTML here -->
  <script src="path-to-your-javascript-file.js"></script>
</body>
</html>
This HTML code sets up a simple HTML document with CDNs for Redux and Redux Toolkit included. The 'path-to-your-javascript-file.js' is a placeholder for the actual path to the JavaScript file where you would have the code from the first snippet. This file needs to be updated with the actual path to the JavaScript code that works with `createEntityAdapter`.
body {
  font-family: Arial, sans-serif;
}

/* Add your CSS styling here */
/* This is just a placeholder for actual CSS styles; no direct relation to createEntityAdapter. */
This CSS snippet provides a minimal styling example setting the font for the body element. The comment indicates that actual CSS styling related to the specific UI elements can be defined in this section.