All files / pages/admin/CreateUser/components UsernameGenerator.tsx

100% Statements 13/13
83.33% Branches 5/6
100% Functions 3/3
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53  2x 2x 2x               2x 3x 3x 3x       1x     2x                 4x   3x           4x                         2x  
import React from "react";
import { Input, Form, Spin, Alert } from "antd";
import { useQuery } from "react-query";
import { UserAPICaller } from "../../../../services/apis/user.api";
 
interface UsernameGeneratorProps {
  label: string;
  firstName: string;
  lastName: string;
}
 
const fetchUsername = async (firstName: string, lastName: string) => {
  const encodedFirstName = encodeURIComponent(firstName);
  const encodedLastName = encodeURIComponent(lastName);
  const response = await UserAPICaller.getUsernameGenerated(
    encodedFirstName,
    encodedLastName
  );
  return response.data.result;
};
 
const UsernameGenerator: React.FC<UsernameGeneratorProps> = ({
  label,
  firstName,
  lastName,
}) => {
  const {
    data: username,
    isLoading,
    isError,
  } = useQuery(
    ["username", firstName, lastName],
    () => fetchUsername(firstName, lastName),
    {
      enabled: !!firstName && !!lastName,
    }
  );
 
  return (
    <Form.Item label={label} labelAlign="left">
      {isLoading ? (
        <Spin />
      ) : isError ? (
        <Alert message="Failed to fetch username" type="error" />
      ) : (
        <Input value={username} readOnly disabled />
      )}
    </Form.Item>
  );
};
 
export default UsernameGenerator;