Search code examples
javascriptreactjsecmascript-6es6-promise

Accessing fetch() data that lives in a function


I'm trying to learn React and am attempting to make a calendar for my website that is linked to a public Google Calendar. It took ages to figure out how to get to the information that I needed, but I managed it. Now, I am presented with a problem and it's more vanilla Javascript oriented...

My code looks like this:

import React, { Component } from 'react';

export default class Calendar extends Component {
    async getEventNames() {
        try {
            await fetch('https://clients6.google.com/calendar/v3/calendars/[email protected]/events?calendarId=b2f8g8daabnmpqo43v04s6fl3g%40group.calendar.google.com&singleEvents=true&timeZone=Europe%2FAmsterdam&maxAttendees=1&maxResults=250&sanitizeHtml=false&timeMin=2019-04-01T00%3A00%3A00%2B02%3A00&timeMax=2019-05-06T00%3A00%3A00%2B02%3A00&key=AIzaSyBNlYH01_9Hc5S1J9vuFmu2nUqBZJNAXxs')
                .then(res => {
                    return res.json();
                })
                .then(data => {
                    const nameArr = data.items.map(item => {
                        return item.summary;
                    });
                    console.log(nameArr);
                    return nameArr;
                });
        } catch (err) {
            console.error(err);
        }
    }
    render() {
        const arr = this.getEventNames();
        console.log(arr);
        return <div />;
    }
}

So, I fetch the data from my calendar, turn it into a JSON array, map that into an array and return it. Or at least that's what I'm going for... Notice there are two console.log()s in there. The one inside the getEventNames() function presents the array that I want, but the one in my render() function gives me "Promise {pending}".

I know nothing about Promises and would be up for getting schooled on them, but also can anybody just teach me how to get the array out of my function?

Please, thank you and have nice Easter (or your culture's equivalent Springtime holiday) :)


Solution

  • It's most common to utilize state and componentDidMount, as it's the best place to "load data from a remote endpoint."

    import React, { Component } from 'react';
    
    export default class Calendar extends Component {
      constructor(props) {
       super(props);
    
        this.state = {
          eventNames: []
        }
      }
    
      componentDidMount() {
        fetch('...')
         .then(res => {
           res.json().then(eventNames => {
             this.setState({eventNames});
           });
        }).catch(err => {
         // Error handling
        })
      }
    
      render() {
          console.log(this.state.eventNames);
          return <div />;
      }
    }
    

    I also agree with everything stated in the comments, so please keep those in mind as well :)

    https://reactjs.org/docs/react-component.html#componentdidmount