how can we use data received through axios put request on client side in mern stack?

432 Views Asked by At

I have sent category Id to the Nodejs through this code

const catHandler = async (catId) => {
    const data =  Axios.put('/api/products/categories/filter',  {catId: catId},
        { 
            "headers": { "content-type": "application/json", },
        }
    ).then( categoriesProducts => {
        console.log(categoriesProducts.data.products)
    })
}

and this is my route for this

router.put('/categories/filter', async (req, res) => {
    try {
        const findCategory = await Category.find({ _id: req.body.catId });
        if (findCategory) {
            const productsByCategory = await Product.find(
                { category: req.body.catId }
            ).then(products => {
                res.status(200).json({ products });
            })
        }
    } catch (error) {
        console.log('categories filter error', error)
    }
})

The products of specific category are being shown in the console.log(categoriesProducts.data.products) on the react front end side like below

0: {_id: "5f7c88756746363148792982", name: "Simple Pizza", price: 5.6, image: "1601996916374.jpg", countInStock: 434, …}
1: {_id: "5f7c88976746363148792983", name: "Smoked Pizza", price: 7.8, image: "1601996951114.jpg", countInStock: 88, …}
2: {_id: "5f7c88c56746363148792984", name: "Large Cheezy Pizza", price: 9.4, image: "1601996997474.jpg", countInStock: 434, …}

But I want to display these products on the front end side. I have tried to use axios.get method but with get method how can I can send category Id to backend. So if any one has any idea how to do that Plz guide me.

2

There are 2 best solutions below

0
Abhi Patel On

you can use the query params with get method in node js you can get query params by req.query in nodeJs

example passing category id from front end -

api/products/categories/filter?cid=1

getting query param in the backend

const catId = req.query.cid
2
Alireza Abedi On

You can use below code to pass parameter to API get method.

fetch("/api/products/categories/filter?catId" + catId)
  .then((res) => res.json())
  .then((json) => {
    this.setState({
      Items: json,
    });
  });

And also you first create new state named as Items such as below.

this.state = {
  Items: []
};

And finally Iterate on Items.

BR