英文:
How to use retrieved data from post request in JSX
问题
以下是翻译好的部分:
const handleVerifyData = async() => {
const verifyCall = await reservationsService.verifyQueueReservations(filteredReservationIds)
const verifiedData = verifyCall.data
return verifiedData
}
<Modal
isOpen={modals['carOnPlaceModal']?.isOpened ?? false}
onClose={handleClose}
styles={{
width: "500px",
bodyPadding: "28px 30px"
}}
>
{
verifiedData?.map(info => {
return <Flex key={info.reservationId} style={{ flexDirection: "row", height: "40%", justifyContent: "space-evenly", alignItems: "flex-start" }}>
<Flex style={{ display: "flex", flexDirection: "column" }}>
<Text mb="10px">{info?.vehicleMark} {info?.vehicleModel} ({info?.vehicleBodyType})</Text>
<CarNumberBox title={info.vehicleGovNumber} />
</Flex>
<Flex style={{ display: "flex", flexDirection: "column" }}>
<Text fontSize="base" mb="10px">{T("notifications.car_on_place.form.select_box")}</Text>
<ChakraSelect
value={selectedBoxes[info.reservationId]}
onChange={async (e: any) => {
const boxNumber: number = parseInt(e.target.value);
const res: AxiosResponse<any> =
await reservationsService.getCheckboxAvailability(info.reservationId, boxNumber);
const updatedSelectedBoxes: any = { ...selectedBoxes };
// 如果框被占用但车辆未被清洗
const hasWarning: boolean = res.data?.data?.warning ?? false;
// 如果框被占用但车辆正在清洗
const hasError: boolean = res.data?.data?.error ?? false;
updatedSelectedBoxes[info.reservationId] = boxNumber;
if (hasWarning) {
toggleModal(
"confirmationModal",
true,
{
title: `您确定要更改为 ${boxNumber} 箱吗?`,
handleSubmit: () => {
setSelectedBoxes(updatedSelectedBoxes)
toggleModal("confirmationModal", false, { title: "" })
}
}
)
return;
}
if (hasError) {
toast.error(T("general.error"))
console.log('框警告');
return;
}
setSelectedBoxes(updatedSelectedBoxes);
}}
>
{Array(info?.boxCount).fill(0).map((option: any, index: number) => {
return <option key={index} value={index + 1}>#{index + 1}</option>;
})}
</ChakraSelect>
</Flex>
</Flex>
})
}
</Modal>
"verifiedData" 是您想要在该函数之外自由访问的值。谢谢您提前的感谢。
英文:
I am retrieving data from post request which is simple object. In order to retrieve data i need to use await operator and as far as I know await can be used only in async functions. If I use async function then how to access that data outside that async function in my JSX ? or is it possible to retrieve data from post request without await ? Here is the code:
const handleVerifyData = async() => {
const verifyCall = await reservationsService.verifyQueueReservations(filteredReservationIds)
const verifiedData = verifyCall.data
return verifiedData
}
<Modal
isOpen={modals['carOnPlaceModal']?.isOpened ?? false}
onClose={handleClose}
styles={{
width: "500px",
bodyPadding: "28px 30px"
}}
>
{
verifiedData?.map(info => {
return <Flex key={info.reservationId} style={{ flexDirection: "row", height: "40%", justifyContent: "space-evenly", alignItems: "flex-start" }}>
<Flex style={{ display: "flex", flexDirection: "column" }}>
<Text mb="10px">{info?.vehicleMark} {info?.vehicleModel} ({info?.vehicleBodyType})</Text>
<CarNumberBox title={info.vehicleGovNumber} />
</Flex>
<Flex style={{ display: "flex", flexDirection: "column" }}>
<Text fontSize="base" mb="10px">{T("notifications.car_on_place.form.select_box")}</Text>
<ChakraSelect
value={selectedBoxes[info.reservationId]}
onChange={async (e: any) => {
const boxNumber: number = parseInt(e.target.value);
const res: AxiosResponse<any> =
await reservationsService.getCheckboxAvailability(info.reservationId, boxNumber);
const updatedSelectedBoxes: any = { ...selectedBoxes };
// If the box is taken but it car is not being washed
const hasWarning: boolean = res.data?.data?.warning ?? false;
// If the box is taken but it the car is being washed
const hasError: boolean = res.data?.data?.error ?? false;
// const hasValidationError: boolean = Object.values(updatedSelectedBoxes).some((e: any) => e === boxNumber) ?? false;
updatedSelectedBoxes[info.reservationId] = boxNumber;
if (hasWarning) {
toggleModal(
"confirmationModal",
true,
{
title: `დარწმუნებული ხართ, რომ გსურთ ${boxNumber} ბოქსის შეცვლა`,
handleSubmit: () => {
setSelectedBoxes(updatedSelectedBoxes)
toggleModal("confirmationModal", false, { title: "" })
}
}
)
return;
// If denied pass () => {}
// If accepted
//const updatedSelectedBoxes: any = { ...selectedBoxes };
// If CheckBoxAvailability returns no warning or errors change the value
// updatedSelectedBoxes[info.reservationId] = e.value;
// setSelectedBoxes(updatedSelectedBoxes);
}
if (hasError) {
toast.error(T("general.error"))
console.log('Warning for box');
return;
}
// // If CheckBoxAvailability returns no warning or errors change the value
setSelectedBoxes(updatedSelectedBoxes);
}}
// options={generateOptions(info?.boxCount || 0)}
>
{Array(info?.boxCount).fill(0).map((option: any, index: number) => {
return <option key={index} value={index + 1}>#{index + 1}</option>;
})}
</ChakraSelect>
</Flex>
</Flex>
})
}
</Modal>
verifiedData is the value i wanna access outside that function freely. Thanks in advance.
答案1
得分: 2
在渲染中使用此值时:
verifiedData?.map(info => {
那么这个值应该存在于state中,对吗?类似这样:
const [verifiedData, setVerifiedData] = useState([]);
在这种情况下,尝试让渲染本身等待结果是错误的方法。相反,函数应该更新状态:
const handleVerifyData = async () => {
const verifyCall = await reservationsService.verifyQueueReservations(filteredReservationIds);
const verifiedData = verifyCall.data;
setVerifiedData(verifiedData);
}
当状态更新时,组件将使用新数据重新渲染。
另外,要注意变量命名。你当前遮蔽了状态变量:
const verifiedData = verifyCall.data;
随着时间的推移,这可能很容易导致混淆和错误。你可以完全消除遮蔽的变量:
const handleVerifyData = async () => {
const verifyCall = await reservationsService.verifyQueueReservations(filteredReservationIds);
setVerifiedData(verifyCall.data);
}
英文:
Since you're using this value in the rendering:
verifiedData?.map(info => {
Then presumably this value exists in state, no? Something like this:
const [verifiedData, setVerifiedData] = useState([]);
In which case trying to make the rendering itself wait for the result is the wrong approach. Instead, the function should update state:
const handleVerifyData = async() => {
const verifyCall = await reservationsService.verifyQueueReservations(filteredReservationIds);
const verifiedData = verifyCall.data;
setVerifiedData(verifiedData);
}
When state is updated, the component will re-render with the new data.
As an aside, be careful with variable naming. You are currently shadowing the state variable here:
const verifiedData = verifyCall.data;
Over time this could easily lead to confusion and bugs. You can eliminate the shadowed variable entirely:
const handleVerifyData = async() => {
const verifyCall = await reservationsService.verifyQueueReservations(filteredReservationIds);
setVerifiedData(verifyCall.data);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论