Problem with infinite call API on React hooks

Ionut :

Hy, I try to make a grid with filter in react hooks with material ui. So far I create the grid, the filter option, the method from API call and everythings works just fine, but my API is call on infinite loop.

This is my API CALL:

 const  HeadQuartersGet = async (filterOptions) => {
  var url = HEADQUARTERS_API_URL +"/isActiv&headQuartersName&headQuartersCode";
  url = InsertParamsToURL(url, filterOptions);
  var data = [];  
  async function fetchData()
  {
    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");
    var requestOptions = 
    {
      method: 'GET',
      headers: myHeaders,             
      redirect: 'follow'
    };

    var json = await fetch(url, requestOptions)
          .then(response => { return response.json(); })
          .then(result => { return result; })
          .catch(error => { return error; })
          data =  json;
  }
  await fetchData();  
  return data;
};

To take the data and write in the grid i use this:

 const [data, setData] = useState({});
  HeadQuartersGet(filterOptions).then(result =>{ setData(result); });

  var rows = [];
  for (var i = 0; i<data.length - 1; i++)  
    for(var j = 0; j<data[0].length; j++)  
      rows.push(createData(data[i][j].id, data[i][j].headQuartersName, data[i][j].headQuartersCode, data[i][j].headQuartersDescription, data[i][j].longitute, data[i][j].latitude, data[i][j].isActiv));

function createData(HeadQuartersId, HeadQuartesName, HeadQuartersCode, HeadQuartersDescription, IsActiv) {  
  return { HeadQuartersId, HeadQuartesName, HeadQuartersCode, HeadQuartersDescription, IsActiv };
}

And for the filters I use this:

 const [filterOptions, setFilterOptions] = useState({isActiv: '1'});
 const onChangeFilters = e => {
     setFilterOptions({ ...filterOptions, [e.target.name]: e.target.value })
  }

  const submitFilterOptions = e =>{
    e.preventDefault(); 
  }

MY filter method doesn't work now because the DOM is rendering on infinite loops and when a give a value in filters he filter anyway. enter image description here Can someone help me with the infinite loop ?

Akki :

Updating a state value triggers re-render.

Since you are doing an API call and updating the state, your component is re-rendering, doing the API call again and stuck in this infinite loop.

Solution: Move your API call inside useEffect hook like this.

useEffect(() => {
  HeadQuartersGet(filterOptions).then(result =>{ setData(result); });

  return () => {
  // cancel your api calls here so that there won't be any data leaks
  }

}, []);

The above code will fetch the data you want and update your state once when your component is mounted.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=32017&siteId=1