0

I'm setting a script in my HTML for a geoplugin, assigning the results to the window, and trying to access the variables in a component. The issue is, in the component, I can console.log(window) and see the variables, but any dot notation results in undefined.

Here's the script in my HTML:

<script type="text/javascript">
   setupGeo = (o) => {
     //This is one way I've tried it, setting a Geo object
     window.Geo = {};
     Geo.geoplugin_city = o.city;
     Geo.geoplugin_region = o.region;
     console.log(Geo.geoplugin_city); //works and returns my city
     console.log(Geo.geoplugin_region); //works and return my state

     //This is a second way I've tried it, assigning it to a function that 
        //returns the variable
     window.geoplugin_latitude = function() { return o.lat; };
     window.geoplugin_longitude = function() { return o.lon; };
     console.log(window.geoplugin_longitude); //returns function
     console.log(window.geoplugin_longitude); //return function 
   }
</script>
<script type="text/javascript" src="//extreme-ip-lookup.com/json/? 
  callback=setupGeo" async></script>

As you can see, the script is working as intended. I tried two different ways to and included them both as examples.

In my React component, I am using a ComponentDidMount method to retrieve the values and will eventually set them to state.

Here's the problem: I can console window and see all values, but when I try to dot notation in I get undefined.

componentDidMount() {

    console.log('componentmounted', window)
    // Window ...{Geo:{geoplugin_city: "MyCity", geoplugin_region: "MyState"}}
    // ...geoplugin_latitude: f() ... geoplugin_longitude: f()

    console.log('componentmounted', window.Geo) // undefined
    console.log('componentmounted', window.geoplugin_latitude) //returns 
      //function
    console.log('componentmounted', window.geoplugin_latitude()) //gives error 
      //that window.geoplugin_latitude isn't a function
}

So, I can see the window variables I need, I just get access them inside the Window object. I've done research on how to use the Window Object, but that isn't the issue since I can see the variables in the Window Object. They just become undefined when I try to get to them for use. I've also tried with ComponentWillMount and even UNSAFE_componentWillMount(), but those aren't the issue since I'm retrieving the variables in Window.

Any ideas on how React works that is making this an issue, and how I can go into the Window to get the variables?

Cameron
  • 567
  • 1
  • 5
  • 13

0 Answers0