Getting Selectors in Redux
Sometimes it is very useful to get rid of unnecessary code in an application, as well as encapsulate data.
Let's open our grocery app. Notice that in several places in the app we use selectors to pull out a slice of grocery items to do something with it.
Now we'll open our productsSlice.js
, go to the very end of the file and add a couple of lines of code, in which we'll write two selectors and export them. We'll have one function to get all the products:
export const selectAllProducts = (state) => state.products.products
And after it the second one is to get one product by id:
export const selectProductById = (state, productId) =>
state.products.products.find((product) => product.id === productId)
Of course, you may have a fair question - where did we get such a bells and whistles: state.products.products
? The answer is simple, after all, in the last lesson we changed the structure of the slice and now our products will be in the form of an array in a separate property products
of the products slice state.products
(remember that here state
is the root object of the Redux state, which contains all the slices).
So we've just moved the code for the selector functions into one place in the app, and now we need to make the appropriate changes where we use them. Let's start with the ProductsList.jsx
file. We'll import selectAllProducts
into it, since that's where we'll need to get all the products:
import { selectAllProducts } from './productsSlice'
And at the beginning of the code of the function ProductsList
, we replace:
const products = useSelector((state) => state.products)
On the line:
const products = useSelector(selectAllProducts)
Now let's move on to the file ProductPage.jsx
. Here we needed a product by id. Let's replace the line (don't forget about import):
const product = useSelector((state) =>
state.products.find((product) => product.id === productId)
)
To:
const product = useSelector((state) => selectProductById(state, productId))
Make a similar replacement yourself in the file EditProductForm.jsx
. Here we also need a product by id.
Remember that such optimization is only for your convenience and you can do it when you consider it necessary and convenient. And in our example, imagine that we would write the selector function code in different places each time, and then change the state structure, and then have to correct it in all components.
Open your application with students. Open the file studentsSlice.js
in it. At the very bottom of the file, write and export, as shown in the lesson, two selectors for getting all students selectAllStudents
and for getting one student by id selectStudentById
.
Now import selectAllStudents
and selectStudentById
into StudentsList.jsx
, StudentPage.jsx
and EditStudentForm.jsx
files, make the appropriate changes in these files as shown in the tutorial.