Apologies relatively new to react
When i use the code below when the line setDataVals(await MultipleDataSet(Multiple, CheckIds))
runs it creates a never ending loop of looking up this data and then updating the state
const [arrCheckVals, setCheckVals] = useState('');
const [arrDataVals, setDataVals] = useState([]);
const [arrCheckDates, setArrCheckDates] = useState('');
async function MultipleDataSet(CheckNames, IDs) {
const promises = [];
const OutOfLoopData = [];
CheckNames.split(",").map(entry => {
const InLoopData = []
const result = axios.get('http://localhost:8080/check/chkmeas/vals/'+encodeURI(entry)+'/'+encodeURI(IDs))
.then((response) => {
//Set Response Data
response.data.map((item,key)=> {
InLoopData.push(item.Feild_Value)
})
promises.push(result);
OutOfLoopData.push(InLoopData)
return(InLoopData)
})
.catch('API Call 4 - Error: '+console.error);
})
const results = await Promise.all(promises)
return(OutOfLoopData)
}
async function LoadData() {
var CheckIds = await CheckLookupIDs() //Line ID's
var CheckAPI = APIURL_3+FID+'/'+CheckIds //Lookup API Address
setCheckVals(await CheckVals(CheckAPI)) //Lookup API Response
setArrCheckDates(await CheckDates(CheckAPI))
setDataVals(await MultipleDataSet(Multiple, CheckIds))
return('')
}
LoadData()
I have tried removing other useState functions, I have rearranged the function, i have tried different methods in the function and i just can’t prevent it from being in a never ending loop until it runs out of resources
2
Answers
On every
setDataVals
(and other states), you’ll trigger a new function calculation. However, in that function there’s aLoadData
call, which starts a new cycle.Wrap the
LoadData
inside auseEffect
:That will trigger the cycle once only.
Everytime there’s any state update, the function LoadData would be called according to your code.
We use React’s useEffect hook for all such API calls or functions we need to call just once.
useEffect with empty dependency array would trigger just once.
So, you can go with
Otherwise, it’d always go in an infinite loop if you directly call the function.