0

I am trying to load events from google calendar api which I fetch with gapi.client.request, the problem is that I can't figure a way how to use async/await properly. My events load after my presentational components. I've used async await before and it worked properly with fetch and other APIs. Is there some other way to wait for google.thenable object. Since it's promise like I thought that it would be easier to handle like I handled promises with fetch before. I'm utterly lost here, any help would be appreciated.

const [events, setEvents] = useState([]);

useEffect(() => {
    getEvents();
});

async function get(){
    await getEvents();
}

function getEvents(){
        init()
            .then(() => {
                return gapi.client.request({
                    'path': `https://www.googleapis.com/calendar/v3/calendars/${CALENDAR_ID}/events`,
                })
            })
            .then((res) => {
            const allEvents = res.result.items;
            setEvents(sortedEvents);
        }, (reason) => {
            console.log(reason);
        });
}

Events don't load before components so they aren't being waited properly. I would like my events to be load asynchronously so that they show simultaneously with other presentational components.

Johnn
  • 47
  • 1
  • 2
  • 9

1 Answers1

0

It seems you have some small problems in your code.

First of all, don't forget to make your getEvents() function asynchronous.

Secondly, remember to add a second parameters on your useEffect() method to stop the function from triggering on every single update.

So, you code should look like this:

const [events, setEvents] = useState([]);

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

async function get(){
    await getEvents();
}

async function getEvents(){
        init()
            .then(() => {
                return gapi.client.request({
                    'path': `https://www.googleapis.com/calendar/v3/calendars/${CALENDAR_ID}/events`,
                })
            })
            .then((res) => {
            const allEvents = res.result.items;
            setEvents(sortedEvents);
        }, (reason) => {
            console.log(reason);
        });
}

You might want to read some more on how to handle APIs with React, here is a good resource for you.

Hope this helps.

ZektorH
  • 2,680
  • 1
  • 7
  • 20