Can't get IP address to display. Only display's ...

import React, { Component } from "react";

var xhr;

class IPAddressContainer extends Component {
    constructor (props) {
        super (props);

        this.state = {
            ip_address: "..."
        };

        this.processRequest = this.processRequest.bind(this);
    }

    componentDidMount () {
        xhr = new XMLHttpRequest ();
        xhr.open("GET", "https//ipinfo.io/json", true);
        xhr.send();

        xhr.addEventListener("readystatechange", this.processRequest, false);
    }

    processRequest () {
        if (xhr.readyState === 4 && xhr.status === 200 ) {
            var response = JSON.parse (xhr.responseText);

            this.setState ( {
                ip_address: response.ip
            });
        }
    }
    
    render () {
        return (
        <div>{this.state.ip_address}</div>
        );
    }
}

export default IPAddressContainer;

Do you see any errors in your developer tools’ Console?

Yes:

Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse ()
at IPAddressContainer.processRequest

You don’t need a space between JSON.parse and (xhr.responseText). It should be:

var response = JSON.parse(xhr.responseText);

Does changing the spacing make the error go away?

No, I still get the error:

Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse ()
at IPAddressContainer.processRequest

Seems like you need a :: "https://ipinfo.io/json"

Good catch. Now I get 3 separate errors:

Failed to load resource: the server responded with a status of 429 ()

Unchecked runtime.lastError: The message port closed before a response was received.
localhost/:1

Error handling response: TypeError: Cannot read property ‘loggedOut’ of undefined
at chrome-extension://kcnhkahnjcbndmmehfkdnkjomaanaooo/contentscript.js:167:137

HTTP 429 is ‘too many requests’, so it might not be something you can resolve yourself given that you’re talking to an external service.

Ah! You can use my app key to work around that: IPAddress from React book component only works w/ "on your network" - #15 by kirupa

Note that the best approach is for you to register your own free version of the API from ipinfo.io, for my version gets exhausted by other users of it very quickly :train:

:slight_smile:

1 Like