DEV Community

Breno Novelli
Breno Novelli

Posted on

useIpAdrress()

useIpAddress.ts

import axios from 'axios';
import { useCallback } from 'react';

/**
 * Hook para retornar o IP do usuário.
 *
 * @example
 * const [ipAddress] = useIpAddress();
 * ip_address: await ipAddress(),
 *
 * @return String com o endereço de IP do usuário
 */

const useIpAddress = () => {
  const ipAddress = useCallback(async () => {
    const { data } = await axios.get('https://ipv4.icanhazip.com');

    return data;
  }, []);

  return [ipAddress];
};

export { useIpAddress };

Enter fullscreen mode Exit fullscreen mode

Component.tsx

import { useIpAddress } from 'hooks/useIpAddress';

const [ipAddress] = useIpAddress();

const data = { ip_address: await ipAddress(), ...rest};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)