Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function gets called multiple times in react

I would like to know why the function gets called multiple times wheh dispatch. Also, is there any better way to do,

getData = (value) =>{
  const body = {
    value: value,
    cn: "TH"
  }
return body;
}

renderData(){
  console.log("starts");
  this.props.dispatch(queryData(this.getData(10)));// called repeatedly 
}

render(){
  return(
   <div>{this.renderData()}</div>
  ) 
}

I have updated the different scenario by same type, I need to know is there any other better way to.

scenario 2

getData = () =>{
  const body = {
    value: value,
    cn: "TH"
  }
return body;
}
componentDidMount=()=>{
  this.props.dispatch(queryData(this.getData()))
}
componentDidUpdate = () => {
const {allstate} = this.props.querydata 
  if(this.props.querydata){
    this.renderState(allstate);
  }
}
renderState = (data) => {
  const getId = data.map(e=>e.id); //will get array of values [2, 3, 4]
  getid.map(e=>
    this.props.dispatch(queryState(e))); //for every id dispatch props, 
  )
}
render(){
  // will gets this by componentDidMount call
  return (
    <div>

   </div>
  )
}
like image 212
miyavv Avatar asked Jan 15 '20 03:01

miyavv


People also ask

Why is my function being called twice in React?

The reason for this is for paving the way for a feature that isn't in React yet, so as far as React 18 is concerned, there is no reason. For React Hooks in React 18, this means a useEffect() with zero dependencies will be executed twice.

How do you stop multiple clicks on a React?

To prevent multiple button clicks in React: Set an onClick prop on the button, passing it a function. When the button gets clicked, set its disabled attribute to true .

Why does React render so many times?

The issue is that the setCounter function gets invoked when the component renders, updates the state, which causes a re-render and does that infinitely. You could solve the error by passing an initial value or a function to the useState() hook to initialize the state. Copied!


1 Answers

When there is render in view ,renderData function gets called which dispatch some action, and again this make your component re-render. One solution can be move your this.renderData() function outside the render , may be in constructor or componentDidMount

like image 147
Kais Avatar answered Sep 29 '22 12:09

Kais