Getting data from store in component in Redux

In this lesson we will display data from the store in a React component.

Let's open our product app, go to the parts/products folder and create a ProductsList.jsx file in it. First, import the useSelector hook into it, with which we will receive data from the store:

parts/products/ProductsList.jsximport { useSelector } from 'react-redux'

Now let's get products from the store. We won't create the selector function separately, we'll write its code right in the parameter for useSelector:

parts/products/ProductsList.jsxexport const ProductsList = () => {
  const products = useSelector((state) => state.products)
}

Then we'll output the products in the standard way in the body of the ProductsList function after the line that gets the products, using map:

parts/products/ProductsList.jsxconst dispProducts = products.map((product) => (
  <div key={product.id}>
    <h3>{product.name}</h3>
    <p>{product.desc.substring(0, 100)}</p>
    <p>Price: {product.price}</p>
    <p>Amount: {product.amount}</p>
  </div>
))

And below we will output dispProducts in the following layout:

parts/products/ProductsList.jsxreturn (
  <div>
    <h2>Products</h2>
    {dispProducts}
  </div>
)

Now all that's left is to display our product list on the main page. Let's open the root.jsx file and fix the header:

app/root.jsx<h2>This is my first Redux app!</h2>

Next one:

app/root.jsx<h2>My Products App</h2>

Then we import the ProductsList component into the file:

app/root.jsximport { ProductsList } from '../parts/products/ProductsList'

And we'll insert it into the div with the ID main-page right after the closing tag hr:

app/root.jsx<ProductsList />

We launch our application. Our list of two products has successfully appeared on the main page.

Задание 1

Open your students app. Create a file StudentsList.jsx in the students folder.

Задание 2

Get students from the store using the useSelector hook as described in the tutorial. Map all student information fields from the state using map.

Задание 3

Import the resulting StudentsList component into root.jsx and display it on the main page. Make sure all the student information is displayed on the screen.