MyProducts component for shop owners

In contrast to the Products component, the MyProducts component in client/product/MyProducts.js is only for displaying products to sellers so they can manage the products in each shop they own and will be displayed to the end user as pictured in the following screenshot:

The MyProducts component is added to the EditShop view as shown in the following code, so sellers can manage a shop and its contents in one place. It is provided with the shop's ID in a prop so that relevant products can be fetched:

mern-marketplace/client/shop/EditShop.js:

<MyProducts shopId={match.params.shopId}/>

In MyProducts, the relevant products are first loaded in a state with an useEffect hook using the listByShop fetch method, as shown in the following code:

mern-marketplace/client/product/MyProducts.js:

export default function MyProducts (props){
const [products, setProducts] = useState([])
useEffect(() => {
const abortController = new AbortController()
const signal = abortController.signal
listByShop({
shopId: props.shopId
}, signal).then((data)=>{
if (data.error) {
console.log(data.error)
} else {
setProducts(data)
}
})
return function cleanup(){
abortController.abort()
}
}, [])
...
}

This list of products is then iterated over with each product rendered in the ListItem components along with edit and delete options, similar to the MyShops list view. The edit button links to the Edit Product view. The DeleteProduct component handles the delete action, and reloads the list by calling an onRemove method passed from MyProducts to update the state with the updated list of products for the current shop.

The removeProduct method, defined in MyProducts, is provided as the onRemove prop to the DeleteProduct component. The removeProduct method is defined as follows:

mern-marketplace/client/product/MyProducts.js:

const removeProduct = (product) => {
const updatedProducts = [...products]
const index = updatedProducts.indexOf(product)
updatedProducts.splice(index, 1)
setProducts(updatedProducts)
}

Then it is passed as a prop to the DeleteProduct component when it is added to MyProducts as shown next:

mern-marketplace/client/product/MyProducts.js:

<DeleteProduct
product={product}
shopId={props.shopId}
onRemove={removeProduct}/>

Implementing a separate MyProducts component this way gives the shop owner the ability to see the list of products in their shop with the option to edit and delete each. In the next section, we will complete the implementation for retrieving different types of product lists from the backend and rendering them as product suggestions for buyers in the frontend.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset