Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React setState in map

I'm trying to transform the data get from my database to state~ but It only caught the last data in my database. I guess I didn't use the react hook right, it kept overwrite the previous state, so cause the problem now. I've tried lots of ways, but it still not works. I hope can find someone to help me in here QQ

Here is my code

const [dataSource, setDataSource] = React.useState([]);
React.useEffect(() => {
    orders.map((data, i) =>
      setDataSource([
        ...dataSource,
        {
          key: i,
          id: helpers.leftPad(data.oid, 6, 0),
          name: data.cname,
          totalPrice: data.total_price === null ? 'No data' : data.total_price,
          orderDate: data.order_date,
        },
      ])
    );
  }, []);

orders are the data came from the backend and it looks like

[...
...
744: {oid: 749, cid: 545, cname: "Jerry", order_date: "2018-09-04", …}
745: {oid: 750, cid: 546, cname: "Kevin", order_date: "2018-09-18", …}
...
...]

Thank you guys, it will help me a lot!!

like image 705
hao Avatar asked Sep 16 '25 21:09

hao


1 Answers

you can also perform this as well.

const [dataSource, setDataSource] = React.useState();
React.useEffect(() => {
    let ordersData = orders.map((order, i) =>
      return  {
          key: i,
          id: helpers.leftPad(order.oid, 6, 0),
          name: order.cname,
          totalPrice: order.total_price === null ? 'No data' : order.total_price,
          orderDate: order.order_date,
        },
    );
    setDataSource(ordersData)

  }, []);
like image 65
Dawood Shahid Avatar answered Sep 18 '25 12:09

Dawood Shahid