UseEffect function to update a state variable

Viewed 110

I am new to react and I need to update the update the state variable in a function every time a function is rendered. This variable is used as a prop to a component.

The code is,

function Cal(props) {
     const [allEvents, setEvents] = useState({ events: [] });
     const [currentYear, setCurrentYear] =useState(moment().year().toString());
     useEffect(() => {
    getEvents();
 
  }, [currentYear]);
  async function getEvents() {
    const yearStart = `${currentYear}-01-01`;
    const yearEnd = `${currentYear}-12-31`;
    const data = await fetchEvents(yearStart, yearEnd, 'Discount', currentLang);
    console.log('data:', data);
    setEvents(data);
    console.log('allEvents:', allEvents);
  }
   return (
       <ChildComp
          eventData={allEvents}
        />
   );
}

UPDATE: I need the function getEvents to be called every time the value of current year is changed.When I console log the value of data, I see the response data. But when I console log allEvents, I always see an empty array. I don't see the value of data updated. ? Any help would be appreciated.

Thanks

3 Answers

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);
  };

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}
        />
   );
}

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