I have several components which uses Devextreme modules to make a particular tasks as follows
import React, { useEffect,useState } from 'react';
import Form, { GroupItem, SimpleItem,ButtonItem } from 'devextreme-react/form';
import apis from '../../../utilities/api-constants';
import TokenSelection from '../../../utilities/token-selection';
import { formatMessage } from 'devextreme/localization';
import Stackplan,{DataTable} from '../../stackplan/stackplan';
import PostAPI from '../../../utilities/postAPIS';
import GetAPI from '../../../utilities/getAPIS';
import { DataGrid } from 'devextreme-react';
import { Column } from 'devextreme-react/data-grid';
function WeightBridge() {
const [initialValues, setInitialValues] = useState({
tokenDetails: '',
operation: 'Inweight',
selectedOptions: '',
aplStackplans:''
})
// const [weight,setWeight]=useState(null)
const handleTokenChanges = (tokenDetails, selectedOptions) => {
setInitialValues(previousValues => ({ ...previousValues, selectedOptions: selectedOptions, tokenDetails: tokenDetails }))
}
// console.count("parent component")
const handleStackData = (selectedStackData) => {
const arrangedData=selectedStackData.map(row => ({
bagtype: row.bagtype,
isPriorityOverride: row.isPriorityOverride,
issilo: row.issilo,
isTemporaryStackUsed: row.isTemporaryStackUsed,
flagRecordExists: row.flagRecordExists,
mappedGenericId: initialValues.tokenDetails.genericid,
mappedGodownUnitId: row.mappedGodownUnitId,
tokenId: initialValues.tokenDetails.tokenid,
mappedStacksId: row.mappedStacksId
}));
setInitialValues(previousValues => ({ ...previousValues, aplStackplans: arrangedData }))
};
// returning function to set the weight
const inweightset = (inweigh) => {
console.count('calling this backfunction',inweigh)
setInitialValues(prevValues => ({
...prevValues,
tokenDetails: {
...prevValues.tokenDetails,
inweight: inweigh,
}
}));
// setWeight(inweigh)
// causing the state to rerender
// return inweigh
};
const handleSubmit=async(e)=>{
e.preventDefault()
const formaDataforapi={
wbweight:{inweight:initialValues.tokenDetails.inweight},
// wbweight:{inweightset},
// wbweight:{weight},
generic:{aplStackplans:initialValues.aplStackplans},
tokenId:initialValues.tokenDetails.tokenid,
}
// api call here for posting data
let apiResult = await PostAPI(apis.ADD_INWEIGHT(initialValues.tokenDetails.transactiontype), formaDataforapi);
alert(apiResult.data)
setInitialValues({
tokenDetails: '',
aplStackplans: '',
operation: 'Inweight',
selectedOptions: ''
});
}
// handling different types of transactions
const HandleTransactionTypes = ( value ) => {
if(value==='ISSUE'){
return (
<GroupItem>
<div>
<DataTable
headers={['TokenNumber','Commodity','Variety', 'RoNumber','PendingQuantity']}
data={[{
'TokenNumber': initialValues.tokenDetails.tokenNum,
'Commodity': initialValues.tokenDetails.commodityname,
'Variety': initialValues.tokenDetails.variety,
'RoNumber':initialValues.tokenDetails.roNumber,
'PendingQuantity': initialValues.tokenDetails.pendingQty,
}]}/>
</div>
<br/>
<div >
<Stackplan
tokenDetails={initialValues.tokenDetails}
operation='Inweight'
onRowSelect={handleStackData}/>
</div>
</GroupItem>
);
}
else if(value==='INTERNALMOVEMENT'){
return (
<React.Fragment>
<DataTable
headers={['TokenNumber' ,'MovementName' ,'Shed' , 'Stack' , 'Commodity' , 'Variety']}
data={[{
'TokenNumber': initialValues.tokenDetails.tokenNum,
'MovementName': initialValues.tokenDetails.friendlyName,
'Shed': initialValues.tokenDetails.shedNameIntMov,
'Stack': initialValues.tokenDetails.stackNameIntMov,
'Variety': initialValues.tokenDetails.variety,
'Commodity': initialValues.tokenDetails.commodityname
}]}/>
</React.Fragment>
);
}
else if(value==='MANDI'){
return (
<GroupItem>
<div>
<DataTable
headers={['TokenNumber','NoofBags','CropYear','BagType','Commodity','declaredweight']}
data={[
{
'TokenNumber': initialValues.tokenDetails.tokenNum,
'NoofBags': initialValues.tokenDetails.noofbags,
'CropYear': initialValues.tokenDetails.cropyear,
'BagType':initialValues.tokenDetails.bagtype,
'Commodity':initialValues.tokenDetails.commodityname,
'declaredweight':initialValues.tokenDetails.declaredweight
}
]}/>
</div>
<br/>
<div>
<Stackplan
tokenDetails={initialValues.tokenDetails}
operation='Inweight'
onRowSelect={handleStackData}/>
</div>
</GroupItem>
);
}
else if(value==='CMR'){
return (
<GroupItem>
<div>
<DataTable
headers={['TokenNumber','NoofBags','MillerName','CropYear','BagType','Commodity','Variety','DumpingArea','declaredweight']}
data={[
{
'TokenNumber': initialValues.tokenDetails.tokenNum,
'NoofBags': initialValues.tokenDetails.noofbags,
'MillerName': initialValues.tokenDetails.millername,
'CropYear': initialValues.tokenDetails.cropyear,
'BagType': initialValues.tokenDetails.bagtype,
'Commodity': initialValues.tokenDetails.commodityname,
'Variety': initialValues.tokenDetails.variety,
'DumpingArea': initialValues.tokenDetails.dumpingareaname,
'declaredweight':initialValues.tokenDetails.declaredweight
}
]}
/>
</div>
<br/>
<div>
<Stackplan
tokenDetails={initialValues.tokenDetails}
operation='Inweight'
onRowSelect={handleStackData}/>
</div>
</GroupItem>
);
}
else if(value ==='TRUCKSHIPMENTINWARD' ){
return(
<GroupItem>
<div>
<DataTable
headers={['TokenNumber','NoofBags','Commodity','Variety']}
data={[{
'TokenNumber':initialValues.tokenDetails.tokenNum,
'NoofBags':initialValues.tokenDetails.noofbags,
'Commodity':initialValues.tokenDetails.commodityname,
'Variety':initialValues.tokenDetails.variety
}]}/>
</div>
<br/>
<div >
<Stackplan
tokenDetails={initialValues.tokenDetails}
operation='Inweight'
onRowSelect={handleStackData}/>
</div>
</GroupItem>
)
}
else if(value===('TRUCKSHIPMENTOUTWARD'||'RAILHEAD_MOVEMENT')){
return(
<GroupItem >
<div>
<DataTable
headers={['TokenNumber','Commodity','Variety']}
data={[{
'TokenNumber':initialValues.tokenDetails.tokenNum,
'Commodity':initialValues.tokenDetails.commodityname,
'Variety':initialValues.tokenDetails.variety
}]}/>
</div>
<br/>
<div>
<Stackplan
operation='Inweight'
tokenDetails={initialValues.tokenDetails}
onRowSelect={handleStackData}/>
</div>
</GroupItem>
)
}
else if(value==='PHYSICAL_VERIFICATION'){
return (
<GroupItem caption='Select stack for weighment'>
<PHYSICAL_VERIFICATION tokenDetails={initialValues.tokenDetails}/>
</GroupItem>
)
}
else
return null;
// FOR 'OTHERS' TYPE OF TRANSACTION NONE IS RETURNED
}
return (
<div className={'content-block'}>
<div className={'dx-card responsive-paddings'}>
<form >
<Form id="form">
<GroupItem caption={formatMessage('InWeight')}>
<SimpleItem>{formatMessage('CaptionsTop')}</SimpleItem>
<GroupItem colCount={2}>
<GroupItem colSpan={2}>
<TokenSelection
selectedOptions={initialValues.selectedOptions}
operation='Inweight'
handleTokenChanges={handleTokenChanges}
Url={apis.GET_TOKENS_FOR_INWEIGHT}/>
</GroupItem>
<SimpleItem id='text'
dataField={'TransactionType'}
label={{text:formatMessage("TransactionType")}}
editorOptions={{
readOnly: true,
value: initialValues.tokenDetails ? initialValues.tokenDetails.transactiontype : ''
}}/>
</GroupItem>
<GroupItem>
{initialValues.tokenDetails && HandleTransactionTypes(initialValues.tokenDetails.transactiontype)}
</GroupItem>
<SimpleItem>
{initialValues.tokenDetails&&<MemoizedWeightCapture inweightset={inweightset}/>}
</SimpleItem>
</GroupItem>
{/* <ButtonItem horizontalAlignment="left" buttonOptions={{ text: formatMessage('Save'), type: 'success', useSubmitBehavior: {valuation} }} onSubmit={handleSubmit}/> */}
<ButtonItem horizontalAlignment="left" buttonOptions={{ text: formatMessage('Save'), type: 'success'}} onSubmit={handleSubmit}/>
</Form>
</form>
</div>
</div>
);
}
export default React.memo(WeightBridge)
// component for capturing physical verfication
export function PHYSICAL_VERIFICATION({ tokenDetails }) {
const [Pvtype, setPV] = useState('BABY');
const [selectedShed, setSelectedShed] = useState('');
const [sheds, setSheds] = useState([]);
const [selectedStackType, setSelectedStackType] = useState('');
const [stacks,setStacks]=useState([])
const [stackdata,setStackdata]=useState('')
useEffect(() => {
fetchingApiData();
async function fetchingApiData() {
try {
const PVdetails = await GetAPI(apis.GET_PVINSTANCE_DETAILS(tokenDetails.tokenid));
const shedsResponse = await GetAPI(apis.GET_SHEDS_FOR_STACKS_WEIGHMENT(Pvtype, PVdetails.data.depotPvId));
setSheds(shedsResponse.data);
} catch (error) {
console.error('Error fetching data for sheds:', error);
}
}
}, [Pvtype,tokenDetails]);
// console.count('PV component')
useEffect(()=>{
if(selectedShed){
stackdataapicall()
}
async function stackdataapicall(){
try{
const stackapidata = await GetAPI(
apis.GET_STACKS_FOR_WEIGHMENT_BY_SHED(
selectedShed,
tokenDetails.tokenid,
Pvtype === 'BABY' ? 1 : 2
// for BABY stack it the PVtypevalue is 1 and for the otherPV stacks PVtypevalue is 2
)
)
setStacks(stackapidata.data)
}catch(error){
console.error("can't fetch data for stacks line 355 PHYSICAL_VERIFICATION component",error)
}
}
},[selectedShed,tokenDetails])
useEffect(() => {
if(selectedStackType){
checkforspace()
}
async function checkforspace(){
try {
const responcedata=await GetAPI(apis.CHECK_FOR_STACK_BALANCE(selectedStackType))
if(responcedata?.data.isPending===true){
const formattedstring=formatMessage('AlertweightBridge')
alert(formattedstring)
}
const stackplandata=await GetAPI(apis.GET_STACKS_DETAILS_FOR_PV(selectedStackType))
setStackdata(stackplandata.data)
} catch (error) {
console.error("can't fetch data for checking of space line 352 PHYSICAL_VERIFICATION component",error)
}
}
}, [selectedStackType]);
const handleStackChange = (event) => {
setPV(event.target.value);
};
const handleShedChange = (event) => {
const selectedShedValue = event.target.value;
setSelectedShed(selectedShedValue);
};
const handleStackTypeChange = (event) => {
setSelectedStackType(event.target.value);
};
return (
<div>
<div className='radiobuttons'>
<label>
<input
type="radio"
value="BABY"
checked={Pvtype === 'BABY'}
onChange={handleStackChange}
/>
{formatMessage('BabyStack')}
</label>
<label>
<input
type="radio"
value="NONBABY"
checked={Pvtype === 'NONBABY'}
onChange={handleStackChange}
/>
{formatMessage('OtherStack')}
</label>
</div>
<div style={{ display: 'inline-block' }}>
<label>Select Shed:</label>
<select value={selectedShed} onChange={handleShedChange}>
<option value="">Select Shed</option>
{sheds.map((shed) => (
<option key={shed.shedId} value={shed.shedId}>{shed.shedName}</option>
))}
</select>
<label>Select Stack:</label>
<select value={selectedStackType} onChange={handleStackTypeChange}>
<option value="">Select Stack</option>
{stacks.map((stack)=>(
<option key={stack.stackHistoryId} value={stack.stackHistoryId}>{stack.stackName}</option>
))}
</select>
<DataGrid showBorders={true} dataSource={stackdata} noDataText="Custom No data text">
<Column dataField={'formationdate'} caption={formatMessage('DateofFormation')} allowEditing={false} alignment='center'/>
<Column dataField={'commodity'} caption={formatMessage('Commodity')} allowEditing={false} alignment='center'/>
<Column dataField={'category'} caption={formatMessage('Category')} allowEditing={false} alignment='center'/>
<Column caption={formatMessage('BookBalance')} allowEditing={false} alignment='center'>
<Column dataField={'noofbags'} caption={formatMessage('NoofBags')} allowEditing={false} alignment='center'/>
<Column dataField={'quantity'} caption={formatMessage('Quantity')} allowEditing={false} alignment='center'/>
</Column>
<Column caption={formatMessage('TotalReceipt')} allowEditing={false} alignment='center'>
<Column dataField={'maxBags'} caption={formatMessage('NoofBags')} allowEditing={false} alignment='center'/>
<Column dataField={'maxQuantity'} caption={formatMessage('Quantity')} allowEditing={false} alignment='center'/>
</Column>
<Column caption={formatMessage('Imported')} allowEditing={false} alignment='center'>
<Column dataField={'isImported'} caption={formatMessage('IsImported')} allowEditing={false} alignment='center'/>
<Column dataField={'importedFrom'} caption={formatMessage('Country')} allowEditing={false} alignment='center'/>
</Column>
<Column caption={formatMessage('ModeofPayment')} allowEditing={false} alignment='center'>
<Column dataField={'issueWeighment'} caption={formatMessage('Issue')} allowEditing={false} alignment='center'/>
<Column dataField={'receiptWeighment'} caption={formatMessage('Receipt')} allowEditing={false} alignment='center'/>
</Column>
</DataGrid>
</div>
</div>
);
}
// button for capturing the inweight
export function WeightCapture({ inweightset }) {
const [weight, setWeight] = useState(0);
console.log('this component is rendering line 447')
function scanWeight() {
if (!weight) {
const scannedWeight = parseInt(window.prompt('Enter the weight'));
if (scannedWeight) {
setWeight(scannedWeight);
inweightset(scannedWeight);
}
}
}
console.count('this is counting')
function handleScanAgain() {
setWeight('');
}
return (
<div style={{ display: 'flex', alignItems: 'center' }}>
<label style={{ marginRight: '10px' }}>Tare Weight:</label>
{!weight && <button onClick={scanWeight}>Capture Weight</button>}
{weight && (
<>
<input type='text' value={weight} readOnly style={{ marginRight: '10px' }} />
<button onClick={handleScanAgain}>Scan Again</button>
</>
)}
</div>
);
}
export const MemoizedWeightCapture = React.memo(WeightCapture);
So when the capture weight button is pressed the component captures some integer and stores them in the weight. After that the weight is transfered back to the main component (weightbridge) and the state will be updated there too. Problem: the main problem is when I try to capture the weight the component is rerendering again coming to the initial state again and weight coming to 0 or initial state. I want to remove this error.
I try to change the state setting as shown in the comments but nothing changed. and I even try to remove usestate in my child component(weightcapture) and the phenomenon comes again.