Latest products

On the home page of the MERN Marketplace, we will display five of the latest products added to the marketplace. To fetch the latest products, we will set up a backend API that will receive a GET request at /api/products/latest, as shown in the following code:

mern-marketplace/server/routes/product.routes.js:

router.route('/api/products/latest')
.get(productCtrl.listLatest)

A GET request received at this route will invoke the listLatest controller method. This method will find all products, sort the list of products in the database with the created date field from newest to oldest, and return the first five from the sorted list in the response. This listLatest controller method is defined as follows:

mern-marketplace/server/controllers/product.controller.js:

const listLatest = async (req, res) => {
try {
let products = await Product.find({}).sort('-created')
.limit(5).populate('shop', '_id name').exec()
res.json(products)
} catch (err){
return res.status(400).json({
error: errorHandler.getErrorMessage(err)
})
}
}

To use this API in the frontend, you will also need to set up a corresponding fetch method in api-product.js for this latest products API, similar to other API implementations. This retrieved list will then be rendered in the Suggestions component to be added to the home page. Next, we will discuss a similar API for retrieving a list of related products. 

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

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