I want to search for my product to display on my browser by clicking the search button.
I can search products by Postman API nicely. But, I have no idea to display data by clicking the search button.
product.js
router.get("/find/:id", async (req, res) => {
try {
const product = await Product.findById(req.params.id);
res.status(200).json(product);
} catch (err) {
res.status(500).json(err);
}
});
//GET ALL PRODUCTS
router.get("/", async (req, res) => {
const qNew = req.query.new;
const qCategory = req.query.category;
try {
let products;
if (qNew) {
products = await Product.find().sort({ createdAt: -1 }).limit(1);
} else if (qCategory) {
products = await Product.find({
categories: {
$in: [qCategory],
},
});
} else {
products = await Product.find();
}
res.status(200).json(products);
} catch (err) {
res.status(500).json(err);
}
});
Navbar.js
const Navbar = () => {
return (
<Button>Search</Button>
);
};
export default Navbar;
You're going to want to use Axios to make a request from your react application.
To do this you need to install and require Axios into your react application.
This code will allow you to make a request to your express application:
async function getProduct(productID) {
try {
const response = await axios.get(`/find/${productID}`);
console.log(response);
} catch (error) {
console.error(error);
}
}
This is going to only work when you know what the ID of the product you're searching is. If you have another endpoint on your server to search for a product via name you can change the endpoint accordingly. Here are the Axios docs.
Hope this helps. Thanks!