Redux toolkit createEntityAdaptor

We're going to now show why Redux Toolkit is so awesome. This is a large jump that skips a lot of the "classic Redux" boilerplate, so we apologize if this feels too advanced right now. But, it is the most direct way to get the features we want into our app, so we're taking the leap. You might want to hold onto something.

In this tutorial, we've added a line create missionsAdapter = createEntityAdapter();. Let's look at the official documentation of createEntityAdapter:

A function that generates a set of prebuilt reducers and selectors for performing CRUD operations on a normalized state structure containing instances of a particular type of data object. These reducer functions may be passed as case reducers to createReducer and createSlice. They may also be used as "mutating" helper functions inside of createReducer and createSlice.

Let's focus on the "selectors" for now. missionsAdapter is going to generate selectors, which are as defined by Redux here:

A "selector function" is any function that accepts the Redux store state (or part of the state) as an argument, and returns data that is based on that state.

Okay, so once again redux is creating abstractions around things that are ultimately quite simple- reading from our store. A selector is a function that accepts the store, and returns data. It's always going to represent that concept.

What createEntityAdapter is doing here is generating those selectors for us, so we don't even need to write them.

We start by calling missionsAdapter.getSelectors- which as explained in this lengthy tutorial, generates selectors for us (selectAll and selectById). We rename these to selectAllMissions and selectMissionById. We must pass a small function in here to tell the getSelectors function that we want state.missions slice to do the selecting from.

This all seems really complicated, and you might feel overwhelmed. But don't worry, what we've done is really powerful and will help simplify this boilerplate a lot.

Menu
Lesson 3/6
import { createSlice, createEntityAdapter } from "@reduxjs/toolkit";
// We're now importing the default data
import defaultMissions from "./missionData";
// create an entity adapter!
const missionsAdapter = createEntityAdapter();

const missionsSlice = createSlice({
  name: "missions",
  initialState: {
    missions: defaultMissions,
  },
});

export const { selectAll: selectAllMissions, selectById: selectMissionById } =
  missionsAdapter.getSelectors((state) => state.missions);

export default missionsSlice.reducer;