Helle everyone ,
I was working on react framework and was using a setState to set a value and display it on UI. But it is not immediately updating its value.
whenever I call the computeTotalQty
function to set the value, it sets the value but the change is not reflected in containerList function which updates the value on UI. It displays the value a step later. Same is the case with containerSetList. Whenever the user clicks the removeItem button, it doesn’t immediately remove the item from the screen, though it is removed from the containerSetList
.
Code for it is:
const [containerSetList, setContainerSetList]=useState<containerSet[]>([])
const [totalQty,setTotalQty]=useState(0);
let tempQty=0;
const computeTotalQty= ()=>{
containerSetList.map((item:any)=>{
tempQty=tempQty+item.quantity.value;
})
setTotalQty(tempQty);
}
const ContainerList=()=>{
return(
<div >
<Text alignment="center">
Total Containers: {containerSetList.length} {" "}
Total { unitType == "unit" ? "units" : "Weight"} : {totalQty} {unitType == "unit"?"":"gms"}
</Text>
<Divider/>
<Table headerRows={1} spacing="small" showDividers={true}>
<TableRow>
<TableCell>Container ID</TableCell>
<TableCell>Quantity</TableCell>
<TableCell></TableCell>
</TableRow>
{containerSetList.map((item:any)=>(
<TableRow >
<TableCell>{item.inventoryItem.id}</TableCell>
<TableCell>{item.quantity.value}</TableCell>
<TableCell>
<Button type="secondary" onClick={(e:any)=>removeItem(item)} size="small">
<Icon tokens={CloseMedium} />
</Button>
</TableCell>
</TableRow>
))}
</Table>
<Divider spacingAfter="medium"/>
</div>
)
}
const removeItem=(props:any)=>{
let indexToRemove= containerSetList.indexOf(props);
containerSetList.splice(indexToRemove, 1);
computeTotalQty();
}
return (
<div>
{ContainerList()}
</div>
);
Can anyone please tell me how can I solve it?