React Material Table not reloading while the data is fetched

huangapple go评论59阅读模式
英文:

React Material Table not reloading while the data is fetched

问题

I understand that you want a translation for the provided code and text. Here's the translated code and text without any additional content:

我理解您需要提供的代码和文本的翻译。以下是翻译后的代码和文本,没有附加内容:

我正在尝试学习JS / React,但在制作"simple-shop"项目时遇到了困难。
我尝试异步获取数据然后加载到Material表格中,但不知道哪里出了问题。
表格显示"无记录可显示",但在控制台中我可以看到结果。

这是获取函数:

useEffect(() => {
  axios
    .get('api/OrderData/getAllOrders')
    .then(res => {
      res.data.map(async x => {
        apiData.push({
          orderId: x.orderId,
          orderGUID: x.orderGUID,
          orderName: x.orderName,
          orderDate: dateFormat(x.orderDate, "ddd mmm dd yyyy HH:MM:ss"),
          orderStatus: x.orderStatus,
          contractorId: x.contractorId,
          creatorUsername: x.creatorUsername,
          orderVendor: x.orderVendor,
          magazyn: x.magazyn,
          productId: x.productId,
          orderPayment: await axios
            .get("/api/Payments/getPaymentByOrderGUID?OrderGuid=" + x.orderGUID)
            .then(res => {
              if (res.status === 200) {
                return "Opłacone";
              } else {
                return "Nie opłacone";
              }
            })
            .catch(err => {
              console.log(err);
              return "Nie opłacone";
            })
        });
      });
      //执行其他操作
      console.log(apiData);
      setTableData(apiData);
    })
    .catch(err => {
      console.log(err);
    });

  axios
    .get('api/Contractor/getAllContractors')
    .then(res => {
      res.data.map(x => {
        contractorData.push({
          contractorId: x.contractorId,
          contractorName: x.contractorName,
          contractorSurname: x.contractorSurname,
          contractorIndividualDiscount: x.contractorIndividualDiscount
        });
      });
    })
    .catch(err => {
      console.log(err);
    });
}, []);

以及Material表格设置:

<MaterialReactTable
  displayColumnDefOptions={{
    'mrt-row-actions': {
      muiTableHeadCellProps: {
        align: 'center',
      },
      size: 120,
    },
  }}
  columns={columns}
  data={tableData}
  editingMode="modal" //默认值
  enableColumnOrdering
  enableRowActions
  onEditingRowSave={handleSaveRowEdits}
  onEditingRowCancel={handleCancelRowEdits}
  renderRowActionMenuItems={({ row, closeMenu, table }) => [

当我删除任何async / await子句时,控制台中的结果相同,但数据显示出来了,但问题是,数据显示出来时少了一个值,我的意思是没有orderPayment,因为它显示为Promise,为了解决这个问题,我使用了async/await,但目前无法将其加载到表格中...

英文:

im trying to learn the JS / React, ive stuck with making the simple-shop project.
Im trying to fetch the data async then load to the Material table, but idk what is wrong.
The table says "no record to display", but in the console i can see the result: React Material Table not reloading while the data is fetched

This is the fetch function:

  useEffect(() =&gt; {
axios
.get(&#39;api/OrderData/getAllOrders&#39;)
.then(res =&gt; {
res.data.map(async x =&gt; {
apiData.push({
orderId: x.orderId,
orderGUID: x.orderGUID,
orderName: x.orderName,
orderDate: dateFormat(x.orderDate, &quot;ddd mmm dd yyyy HH:MM:ss&quot;),
orderStatus: x.orderStatus,
contractorId: x.contractorId,
creatorUsername: x.creatorUsername,
orderVendor: x.orderVendor,
magazyn: x.magazyn,
productId: x.productId,
orderPayment:
await axios
.get(&quot;/api/Payments/getPaymentByOrderGUID?OrderGuid=&quot; + x.orderGUID)
.then(res =&gt; {
if(res.status === 200)
{
return &quot;Opłacone&quot;
}else {
return &quot;Nie opłacone&quot;
}
})
.catch(err =&gt; {
console.log(err)
return &quot;Nie opłacone&quot;
}) 
})
})
//do anything
console.log(apiData)
setTableData(apiData)
})
.catch(err =&gt; {
console.log(err)
})
axios
.get(&#39;api/Contractor/getAllContractors&#39;)
.then(res =&gt; {
res.data.map(x =&gt; {
contractorData.push({
contractorId: x.contractorId,
contractorName: x.contractorName,
contractorSurname: x.contractorSurname,
contractorIndividualDiscount: x.contractorIndividualDiscount
})
})
})
.catch(err =&gt; {
console.log(err)
})
}, [])

And the material table settings:

  &lt;MaterialReactTable
displayColumnDefOptions={{
&#39;mrt-row-actions&#39;: {
muiTableHeadCellProps: {
align: &#39;center&#39;,
},
size: 120,
},
}}
columns={columns}
data={tableData}
editingMode=&quot;modal&quot; //default
enableColumnOrdering
enableRowActions
onEditingRowSave={handleSaveRowEdits}
onEditingRowCancel={handleCancelRowEdits}
renderRowActionMenuItems={({ row, closeMenu, table}) =&gt; [

When i delete any async / await clousules im getting same result in console but the data is showing, but the problem is that, the data is showing without one value, i mean without orderPayment, cuz it is showing as Promise, to resolve it i did the async/await but for now i cannot load it to the table...

答案1

得分: 0

I have seen your whole code but It looks like the issue might be related to the fact that setTableData(apiData) is being called outside of the async map function. Since apiData is being populated asynchronously, setTableData is likely being called before apiData has finished being populated, resulting in an empty table.

For fixing your bug, you can use Promise.all to wait for all the promises to resolve before setting the state. Change your code above last axios getAllContractors inside useEffect Please Modify your code by my provided code:

axios
    .get('api/OrderData/getAllOrders')
    .then(res => {
      const promises = res.data.map(async x => {
        const orderPayment = await axios
          .get("/api/Payments/getPaymentByOrderGUID?OrderGuid=" + x.orderGUID)
          .then(res => {
            if (res.status === 200) {
              return "Opłacone";
            } else {
              return "Nie opłacone";
            }
          })
          .catch(err => {
            console.log(err);
            return "Nie opłacone";
          });
        
        return {
          orderId: x.orderId,
          orderGUID: x.orderGUID,
          orderName: x.orderName,
          orderDate: dateFormat(x.orderDate, "ddd mmm dd yyyy HH:MM:ss"),
          orderStatus: x.orderStatus,
          contractorId: x.contractorId,
          creatorUsername: x.creatorUsername,
          orderVendor: x.orderVendor,
          magazyn: x.magazyn,
          productId: x.productId,
          orderPayment: orderPayment
        };
      });
      
      Promise.all(promises).then(apiData => {
        console.log(apiData);
        setTableData(apiData);
      });
    })
    .catch(err => {
      console.log(err);
    });

And you know in the updated code, Promise.all is used to wait for all the promises returned by map to resolve before calling setTableData. This ensures that apiData is fully populated before trying to set the state. If you still face the error then please let me know. I'll guide you more about it.

英文:

I have seen your whole code but It looks like the issue might be related to the fact that setTableData(apiData) is being called outside of the async map function. Since apiData is being populated asynchronously, setTableData is likely being called before apiData has finished being populated, resulting in an empty table.

For fixing your bug, you can use Promise.all to wait for all the promises to resolve before setting the state. Change your code above last axios getAllContractors inside useEffect Please Modify your code by my provided code:

  axios
.get(&#39;api/OrderData/getAllOrders&#39;)
.then(res =&gt; {
const promises = res.data.map(async x =&gt; {
const orderPayment = await axios
.get(&quot;/api/Payments/getPaymentByOrderGUID?OrderGuid=&quot; + x.orderGUID)
.then(res =&gt; {
if (res.status === 200) {
return &quot;Opłacone&quot;;
} else {
return &quot;Nie opłacone&quot;;
}
})
.catch(err =&gt; {
console.log(err);
return &quot;Nie opłacone&quot;;
});
return {
orderId: x.orderId,
orderGUID: x.orderGUID,
orderName: x.orderName,
orderDate: dateFormat(x.orderDate, &quot;ddd mmm dd yyyy HH:MM:ss&quot;),
orderStatus: x.orderStatus,
contractorId: x.contractorId,
creatorUsername: x.creatorUsername,
orderVendor: x.orderVendor,
magazyn: x.magazyn,
productId: x.productId,
orderPayment: orderPayment
};
});
Promise.all(promises).then(apiData =&gt; {
console.log(apiData);
setTableData(apiData);
});
})
.catch(err =&gt; {
console.log(err);
});

> And you know in the updated code, Promise.all is used to wait for all the promises returned by map to resolve before calling setTableData. This ensures that apiData is fully populated before trying to set the state. If you still face the error then please let me know. I'll guide you more about it.

huangapple
  • 本文由 发表于 2023年4月6日 22:02:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75950416.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定