Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

data get from axios not sorted correctly

I need to get productId from query then get all data related to that product. This data should be sorted by createdAt month (id).

I tried .sort() but that didn’t sort my data with proof that whenever i click on send button on postman, i receive untidy data.

API:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//...
router.get("/income", verifyTokenAndAdmin, async (req, res) => {
    const productId = req.query.pid;
    console.log(productId);
    //...

product.jsx:

useEffect(() => {
    const getStats = async () => {
      try {
        const res = await userRequest.get("orders/income?pid=" /*+productId */);
        const list = res.data.sort((a, b) => {
          return a._id - b._id;
        });
        list.map((item) =>
          setPStats((prev) => [
            ...prev,
            { name: MONTHS[item._id - 1], Sales: item.total },
          ])
        );
      } catch (err) {
        console.log(err);
      }
    };
    getStats();
  }, [productId, MONTHS]);

How to properly sort my data received from axios?

I tested Axios URL using postman and get method (localhost:5000/api/orders/income?pid=), it shows list of id (months) and total sales for each month:

[
  {
    "_id": 7,
    "total": 170
  },
  {
    "_id": 6,
    "total": 224
  },
  {
    "_id": 8,
    "total": 200
  }
]

>Solution :

Try this

   const list = res.data.sort((a, b) => {
          if(a._id>b._id){
             return -1;
          }
          if(a._id<b._id){
             return 1;
          }
          return 0;
        });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading