-1

I have a complex state calculationResults as

export interface ICalculationResult {
hw: IHwCalculationResult;
}

export interface IHwCalculationResult {
header: IHwCalculationResultHeader;
agreements: IAgreementItem[];
}

export interface IAgreementItem {   
agreementRows: IAgreementRow[];
}

I want to remove the agreements pertaining to a product from the calculationResults.hw.agreements and then push the agreements received from the api.

I'm using immer since the object has many properties and the record count will be more than 5000

 const nextState = produce(calculatedResults,(draftstate: any) =>{
      if(allsite == "1"){      
        var indices: any = [];            
        draftstate.hw.agreements.forEach(function(value:any,pos: number){
          if(value.boQItem.id == productNo)
          {
            indices.push(pos);
          }
        });
          for(var index = indices.length-1;index>=0;index--)
          {
            draftstate.hw.agreements.splice(indices[index],1);
          }   
          draftstate.hw.agreements.push(...data.hw.agreements);   
        
        }
    });

Do I need to set the state as setCalculationResults(newState)? But when I do it, there's a compiler error that newState is incompatible for calculationResults

Raida Adn
  • 405
  • 1
  • 6
  • 17
  • Do it like this. `setCalculationResults(produce((draft) => {....})`. Here you can make changes to draft directly. You can follow this example to understand how you can use immer with react. [React & Immer](https://immerjs.github.io/immer/example-setstate) – Muhammad Nouman Rafique Nov 16 '22 at 19:34
  • @Mohammed Nouman Rafique I modified the code to as suggested. But I get error, cannot read properties of undefined (reading 'hw') – Raida Adn Nov 17 '22 at 06:34

1 Answers1

0

As per @Muhammad Nouman Rafique, I tired using producer inside setCalculationResults but that threw the error cannot read properties of undefined(reading 'hw'). In this scenario the produce method is not able to find the initial state for the draft to take. Hence it is becoming null and threw the error. The syntax seems changed than what the documentation says. So here is how I could update the state immutably.

 setCalculationResults(produce(draft =>{},calculationResults));

So my overall code looks like below,

if(allsite == "1"){  
setCalculationResults(produce((draftstate: any) =>{              
var indices: any = [];            
draftstate.hw.agreements.forEach(function(value:any,pos: number){
   if(value.boQItem.id == productNo)
   {
   indices.push(pos);
   }
  });
  for(var index = indices.length-1;index>=0;index--)
  {                
   draftstate.hw.agreements.splice(indices[index],1);
  }              
   draftstate.hw.agreements.push(...data.hw.agreements);            
  },calculationResults));
}
Raida Adn
  • 405
  • 1
  • 6
  • 17