Reputation: 645
I am new to React and trying to use React Hooks but I am getting error. I am not able to figure out which line of code causing infinite loop as in the console it says
Too many re-renders. React limits the number of renders to prevent an infinite loop
The above error occurred in the <ProcessingInvoiceScreen> component:
in ProcessingInvoiceScreen (at CreateInvoiceBySkid.js:49)
and from line 49 is the const ProcessingInvoiceScreen = () => {
import React, { Component,useState } from 'react';
import {connect} from "react-redux";
import * as actions from "../../../../actions";
class CreateInvoiceBySkid extends Component{
constructor(props){
super(props)
}
async componentDidMount(){
if (!this.props.authenticated && (this.props.authenticated.role !== "superAdmin" || this.props.authenticated.role === "admin" || this.props.authenticated.role === "operator")) {
this.props.history.push('/');
} else {
const user = this.props.authenticated;
this.props.getProcessingInvoiceSkids(user);
this.props.getProducts(user);
}
}
render(){
const ProcessingInvoiceScreen = () => {
const [closedSkids, setclosedSkids] = useState({});
const [selectedSkids, setSelectedSkids] = useState([]);
if(this.props.processingInvoiceSkids){
setclosedSkids(this.props.processingInvoiceSkids.rows);
}
console.log(this.props.processingInvoiceSkids);
return(
<div>
Hello World
</div>
)
}
return(
<div>
<ProcessingInvoiceScreen/>
</div>
)
}
}
const mapStateToProps=(state)=>{
return {
authenticated:state.authenticated,
errorMessage: state.errorMessage,
users: state.users,
processingInvoiceSkids: state.processingInvoiceSkids,
products: state.products
}
};
export default connect(mapStateToProps,actions)(CreateInvoiceBySkid);
What am I doing here that causes infinite loop?
Upvotes: 1
Views: 1298
Reputation: 13078
This line is causing the error. Every time the component is renderer, the setclosedSkids function is called and the component is re-renderer again and again :
if(this.props.processingInvoiceSkids){
setclosedSkids(this.props.processingInvoiceSkids.rows);
}
Move this block to an useEffect callback function:
const ProcessingInvoiceScreen = ({processingInvoiceSkids}) => {
const [closedSkids, setclosedSkids] = useState({});
const [selectedSkids, setSelectedSkids] = useState([]);
useEffect(()=> {
if(processingInvoiceSkids){
setclosedSkids(processingInvoiceSkids.rows);
}
}, [processingInvoiceSkids.rows])
return(
<div>
Hello World
</div>
)
}
I recommend to move the function out of the parent component. Then in parent component:
return(
<div>
<ProcessingInvoiceScreen processingInvoiceSkid={this.processingInvoiceSkid}/>
</div>
)
Upvotes: 2