Зміст курсу
Introduction to Redux
Introduction to Redux
2. Fundamental Concepts
Using Selectors to access State
We don't have direct access to the store from index.js
or other React component files, so we often create selectors to access the state data.
Following is an index.js
script in which we need to access the items in the Todo list from the Redux store to display them on the page:
For that, we can create a selector function. We often create selector functions in the relevant file hence, for extracting data from todo
, we create and export the function from todosSlice
. We add this at the end of todosSlice
:
It's a simple inline function that takes in a state
object and returns a specific part of it: the data in the todos
key. Recall that the structure of the Todo app's state looks something like this:
After that, we can now import the selector function inside index.js
:
We also need to import a function called useSelector
from react-redux
:
Now to use the selector function, we need to call the useSelector
function and pass the selector function selections as an argument. The returned data will be the data we need:
We can then simply use the map
method of the todos
array to map the items in the form of <ul>
elements:
Following is a sandbox version of the final code. Drag from the left to see the code:
To recap, we created and exported a selector function that returned the data from the todo
slice and used it with the help of useSelector
function.
Все було зрозуміло?