Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to fetch google map API in componentDidMount? #4746

Closed
eyexx opened this issue Jul 8, 2018 · 2 comments
Closed

How to fetch google map API in componentDidMount? #4746

eyexx opened this issue Jul 8, 2018 · 2 comments

Comments

@eyexx
Copy link
Contributor

eyexx commented Jul 8, 2018

Question about Next.js

I use React.js + Next.js.

I wanna fetch google map API in this project.

However, I cannot figure out how I can fetch API data in Next.js project.

I tried to fetch in componentDidMount() because I also use Geolocation API and I need to use window object and in Next.js project, I can only access window object in componentDidMount() ( is it my stereotype?).

This is my fetching code.

fetch('https://maps.googleapis.com/maps/api/geocode/json?language=ja&sensor=false&latlng=35.6909389,139.6952959&key=myApiKey')
                               .then(res => {
                                   const resData = res.json();
                                   console.log(data.results[0].formatted_address)

                               })

However, this code does not work. The error message said "formatted_address is not undefined" .

So, I go back to Next.js docs and I found getInitialProps(). When I write code like this

 static async getInitialProps () {
        // if( navigator.geolocation ) {
        //
        // }
        const res = await fetch('https://maps.googleapis.com/maps/api/geocode/json?language=ja&sensor=false&latlng=35.6909389,139.6952959&key=apikey')
        const data = await res.json()

        console.log(data)
        console.log(data.results[0].formatted_address)
        return {  address: data.results[0].address_components[3].long_name }
    }

I can fetch successfully. However, I need to use longitude and latitude values from geolocation API and geolocation API need window object so I only can get these values in componentDidMount(). How I can fetch Google Map API in componentDidMount() ???

@eyexx eyexx closed this as completed Jul 8, 2018
@eyexx
Copy link
Contributor Author

eyexx commented Jul 8, 2018

it is just my mistake. Do not Care!

@ItsTommyGun
Copy link

Hey @Koshukey,
could you please clear up what the problem was and how you solved it?
Thank you, Thomas

@lock lock bot locked as resolved and limited conversation to collaborators Apr 15, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants