1

I'm using dynamic routing in Nextjs, but I was hoping to acquire the client's IP prior to doing Server Side Rendering for purposes of adding headers for Social Media shares.

Here is my code:

 function myIP() {
    const router = useRouter()
    const { id } = router.query; // Destructuring our router object
    
    return returnIP()
        .then((ip) => {
            console.log("It an IP -- " + ip);
            return (
                <>
                <h2>
                  {id} with IP {ip}
                </h2>
                </>
            );
        })
    .catch(error => "Error" )
 }

and

 async function returnIP () {

    let ipresponse = await axios.get(ipurl)
              .catch(errors => console.log(errors));
    let ip = await ipresponse.data;

    console.log("IP is -- : " + ip)
    return ip;
 }

The console statement return fine, but this error is triggered:

Error: Objects are not valid as a React child (found: [object Promise]).

I understand that passing through a Promise is what is triggering that error, but I'm not sure how to go around it at this time. So I'm asking for help, please.

1 Answer 1

3

Cause of type React child does not include type object Promise. I suggest you should useState to return Ip. Example:

function myIP() {
    const router = useRouter()
    const { id } = router.query; // Destructuring our router object
    const [ip, setIp] = useState(<div/>);

    useEffect(() => {
        returnIP()
            .then((ip) => {
                console.log("It an IP -- " + ip);
                const componentIp = <>
                    <h2>
                        {id} with IP {ip}
                    </h2>
                </>;

                setIp(componentIp)
                return componentIp;
            })
            .catch(error => "Error" )
    }, [])

    return ip;
}
Sign up to request clarification or add additional context in comments.

1 Comment

HI Viet, can I follow up with another question? I tried to pass the "id" constant from the dynamic route into returnIP but it is undefined. Would you happen to know why that is? The URL address used was <domain>/posts/102 and the filename is [id].js in the posts directory under pages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.