I am trying to render the following component, which is supposed to take the value of a few account level values and render the subtotal in a div. This is the code
import * as React from 'react';
import { ILiquidiManagerProps } from './ILiquidiManagerProps';
import {AccountValue} from './AccountFields';
import {LiquidTEUR} from './DummyContent';
interface SubtotalState {
Account?: any,
SubtotalValue?: any
}
export default class SubtotalValues extends React.Component<ILiquidiManagerProps, SubtotalState> {
public constructor(props: ILiquidiManagerProps) {
super(props);
this.state = {
Account: LiquidTEUR.Subcategories.find(item => item.Name == this.props.label),
SubtotalValue: 0
}
}
private getText = data => {
this.setState({SubtotalValue: data});
}
private initiateValue = () => {
let Account = this.state.Account;
let subtotal = 0;
Account.Accounts.map((item) => {
subtotal += item.Value;
})
this.setState({SubtotalValue: subtotal});
}
public render(): React.ReactElement<ILiquidiManagerProps> {
this.initiateValue();
return(
<React.Fragment>
<a className="collapsible" href="#">
<div
className={`p-2 text-right value ` + this.props.bgColor + ` font-weight-bold ` + this.props.textColor}
data-date={this.props.date}
data-name={this.props.label}
>{this.state.SubtotalValue}</div></a>
<div className="content hidden">
{this.state.Account.Accounts.map((item, key) => {
return <AccountValue key={key} label={item.Value} getValue={this.getText} subtotal={this.state.SubtotalValue} />;
})}
<span className="add-pos"> </span>
</div>
</React.Fragment>
);
}
}
This is the error message it generates
Uncaught (in promise) Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
I have tried several different ways of setting the state of the subtotal, but I always seem to be getting the same error, and I am not sure where I am causing an infinite loop.
question from:https://stackoverflow.com/questions/65941392/why-does-setstate-cause-my-react-app-go-into-infinite-loop