Reusing data from a slice in Redux
In the last lesson, we added another field to the form for adding a product with a drop-down list for selecting the seller who posts it. Let's assume that now we also need to display this information in several more places in the application. To do this, we will not duplicate the code each time, but simply create a separate component in which we will extract data from the slice and display it in those parts of the application where we need it.
Let's open our application with products. Now let's create another file SellerOfProd.jsx
in the products
folder. First, import the useSelector
hook, with which we will get a slice with the required product:
import { useSelector } from 'react-redux'
Then we will extract the required product from the store by the seller id, which we will pass to our new component in props:
export const SellerOfProd = ({ sellerId }) => {
const seller = useSelector((state) =>
state.sellers.find((seller) => seller.id === sellerId)
)
}
And if there is such a seller, we will return its name, and if not, we will return 'unknown'
:
return <span>by {seller ? seller.name : 'unknown'}</span>
Let's now import our new component into ProductsList.jsx
and insert it into the ProductsList
functions right after the header with the product name. As you can see, we passed it the id in the props:
<SellerOfProd sellerId={product.seller} />
Now if we run our app, add a new product and find it in the list, we will see that it has a seller, and the products automatically added when the app starts will have 'unknown'
.
A small digression: if your eslint in the VS Code editor complains about sellerId
, and the application works, then you can ignore this for now or open the .eslintrc.cjs
file of your application and in rules
add "react/prop-types": "off".
It goes without saying that we would like to add information about the seller on the product page as well. To do this, we will insert this line again in the ProductPage
markup after the heading with the product name and check that everything works:
<SellerOfProd sellerId={product.seller} />
Open your app with students. After studying the lesson material, create a file for the component TeacherForStudent
in the students
folder. As a result, the component should return the teacher's full name, and next to it in brackets the subject he teaches. Find the required teacher using the useSelector
hook. If there is no teacher for this student, output 'anonym'
.
Using the component obtained from the previous task, output the teacher data for each student on the student list page.
Do the same as in the previous task, but for a separate student page.