Home > front end >  data get from axios not sorted correctly
data get from axios not sorted correctly

Time:08-02

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:

//...
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
  }
]

CodePudding user response:

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;
        });
  • Related