Redux toolkit useSelector selectAll selectById
Let's tie everything together and start using our Redux Toolkit slice we've just built in our app.
selectAll example
First, head on over to Missions.js
. You'll see that we're now declaring missions = useSelector(selectAllMissions)
. We need to import useSelector
from react-redux
, which is a custom hook to call our selector from redux. We pass in the selector selectAllMissions
, and just like that, our missions are rendered in the table component.
selectById example
Head over to Mission.js
to see the usage of selectMissionById
, our renamed selectById
selector from missionsSlice.js
. This is a little more involved, as we need to create a new selector, and call selectMissionById
with the state and the id of the current mission, pulled from react router params.
The result? We now are reading data from our redux store and rendering it in our app! Great job. We can use these anywhere in our app, and we don't need to worry if things get updated, the components will automatically rerender with the updated data.
Okay so what about editing our data? How can redux toolkit help us with that?
import { createSlice, createEntityAdapter } from "@reduxjs/toolkit"; import defaultMissions from "./missionData"; const missionsAdapter = createEntityAdapter(); const emptyInitialState = missionsAdapter.getInitialState(); const initialState = missionsAdapter.upsertMany( emptyInitialState, defaultMissions ); const missionsSlice = createSlice({ name: "missions", initialState, }); export const { selectAll: selectAllMissions, selectById: selectMissionById } = missionsAdapter.getSelectors((state) => state.missions); export default missionsSlice.reducer;