⊗jsrxPmWFRSD 14 of 57 menu

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:

import { 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:

export 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:

const 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:

return ( <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:

<h2>This is my first Redux app!</h2>

Next one:

<h2>My Products App</h2>

Then we import the ProductsList component into the file:

import { ProductsList } from '../parts/products/ProductsList'

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

<ProductsList />

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

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

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

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.

enru