skip to Main Content

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


  1. On every setDataVals (and other states), you’ll trigger a new function calculation. However, in that function there’s a LoadData call, which starts a new cycle.

    Wrap the LoadData inside a useEffect:

    useEffect(
        () => {
            LoadData();
        },
        []
    );
    

    That will trigger the cycle once only.

    Login or Signup to reply.
  2. 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

    useEffect(() => {
      // API calls
      LoadData();
    }, []);
    

    Otherwise, it’d always go in an infinite loop if you directly call the function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search