Fetching Toronto's Weather

via https://graphql-weather-api.herokuapp.com

Toronto, CA -- overcast clouds


Here's the code for this page, still a work in progress!

The front matter calls a getWeather function, right now with a hard-coded city name. This function calls fetchAPI, which fetches data from a GraphQL server via plain JavaScript.


    ---
    import BaseLayout from '../../layouts/BaseLayout.astro';
    
    async function fetchApi(city) {
        const response = await fetch("https://graphql-weather-api.herokuapp.com", {
            method:'POST',
            headers: {'Content-Type':'application/json',},
            body: JSON.stringify({
                query: `
                    query getWeather($name:String!) {
                        getCityByName(name: $name){
                            name
                            country
                            weather {
                                summary {
                                    description
                                }
                            }
                        }

                    }
                    `,
                variables: {
                    name: city,
                },
            }),
        })

        const json = await response.json();

        if(json.errors){
            console.log(json.errors);
            throw new Error('Failed to fetch API');
        }
        return json.data;
    }

    async function getWeather(city){
        const data = await fetchApi(city)
        console.log(data)
        return data
    }

    const weather = await getWeather("Toronto");
    ---
    <BaseLayout title = "GraphQL API fetch in Astro" >
        <main>
            <h2>Fetching Toronto's Weather</h2>
            <p> via https://graphql-weather-api.herokuapp.com</p>
            <h3>{weather.getCityByName.name}, {weather.getCityByName.country} -- {weather.getCityByName.weather.summary.description}</h3>
            <hr />
        </main>
    </BaseLayout>