score:0

call the function outside of the useeffect.

function cal(props) {
         const [allevents, setevents] = usestate({ events: [] });

async function getevents() {
      const yearstart = `${currentyear}-01-01`;
      const yearend = `${currentyear}-12-31`;
      const data = await fetchevents(yearstart, yearend, 'hard discount', currentlang);
      console.log('data:', data);
      setevents(data);
      console.log('allevents:', allevents);
    }


     useeffect(() => {
   
    getevents();
  }, [allevents]);
   return (
       <childcomp
          eventdata={allevents}
        />
   );
}

for example ;

useeffect(() => {
    getcountries();
  }, []);

  const getcountries = async () => {
    const response = await fetch("https://covid19.mathdro.id/api/countries");
    const data = await response.json();
    const arrayofcountry = data.countries;

    setcountries(arrayofcountry);
    setloading(false);
  };

score:0

if i understood correctly you only need to fetch the async data once the component is rendered for the first time, so change the useeffect hook to a empty array and it will trigger the hook on the almost equivalent "componentdidmount()"

function cal(props) {
     const [allevents, setevents] = usestate({ events: [] });

     useeffect(() => {
    async function getevents() {
      const yearstart = `${currentyear}-01-01`;
      const yearend = `${currentyear}-12-31`;
      const data = await fetchevents(yearstart, yearend, 'hard discount', currentlang);
      console.log('data:', data);
      setevents(data);
      console.log('allevents:', allevents);
    }
    getevents();
  }, []);
   return (
       <childcomp
          eventdata={allevents}
        />
   );
}

score:0

as per your code, useeffect has dependency [allevents], that means every time allevents changes getevents() will be called,

i believe you just need it first time the component is mounted, so just remove dependency

useeffect(() => {
   
    getevents();
  }, [allevents]);


Related Query

More Query from same tag