-
-
Save ragnaroks/aac4dbe578bcd995cc2c939eb04ffe6e to your computer and use it in GitHub Desktop.
react hook that get client address from IPIFY.ORG
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {useEffect,useState} from "react"; | |
type ClientAddressExportArray = [loading:boolean,error:unknown,data:string|null]; | |
type ipifyData = {ip:string}; | |
const useClientAddress = function () : ClientAddressExportArray { | |
const [loading,loadingSetter] = useState<boolean>(false); | |
const [data,dataSetter] = useState<string|null>(null); | |
const [error,errorSetter] = useState<unknown>(null); | |
useEffect(function(){ | |
fetch('https://api64.ipify.org?format=json').then(function(response){ | |
if(!response.ok){return null;} | |
return response.json(); | |
}).then(function(data){ | |
if(!data){return;} | |
const typeData = data as ipifyData; | |
dataSetter(typeData.ip); | |
}).catch(function(exception){ | |
errorSetter(exception); | |
}).finally(function(){ | |
loadingSetter(false); | |
}); | |
},[dataSetter,errorSetter,loadingSetter]); | |
return [loading,error,data]; | |
}; | |
export default useClientAddress; | |
/* import useClientAddress from 'useClientAddress.ts'; | |
* | |
* const [loading,error,data] = useClientAddress(); | |
* | |
* if(!!error){return <ErrorPanel message={error+''} />;} | |
* if(loading){return <Spinner />;} | |
* return <Panel> | |
* <Field title="IP Address" content={data} /> | |
* </Panel>; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment