DEV Community

loading...

useIpAdrress()

brenonovelli profile image Breno Novelli ・1 min read

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

Discussion (0)

Forem Open with the Forem app