blob: 0061701c7fbbbebe762c22b43770314881cc64bc [file] [log] [blame]
simond47ef9e2022-09-28 22:24:28 -04001import { useEffect, useState } from 'react';
2import usePromise from 'react-fetch-hook/usePromise';
3import { InputAdornment, TextField } from '@mui/material';
4import { SearchRounded } from '@mui/icons-material';
5import authManager from '../AuthManager';
Adrien Béraud88a52442021-04-26 12:11:41 -04006
simond47ef9e2022-09-28 22:24:28 -04007const isInputValid = (input) => input && input.length > 2;
Adrien Béraud88a52442021-04-26 12:11:41 -04008
9export default function UsernameChooser(props) {
simond47ef9e2022-09-28 22:24:28 -040010 const [query, setQuery] = useState('');
Adrien Béraud88a52442021-04-26 12:11:41 -040011
simond47ef9e2022-09-28 22:24:28 -040012 const { isLoading, data, error } = usePromise(
13 () =>
14 isInputValid(query)
15 ? authManager.fetch(`/api/ns/name/${query}`).then((res) => {
16 if (res.status === 200) return res.json();
17 else throw res.status;
18 })
19 : new Promise((res, rej) => rej(400)),
20 [query]
21 );
Adrien Béraud88a52442021-04-26 12:11:41 -040022
23 useEffect(() => {
24 if (!isLoading) {
simond47ef9e2022-09-28 22:24:28 -040025 if (error === 404) props.setName(query);
26 else props.setName('');
Adrien Béraud88a52442021-04-26 12:11:41 -040027 }
simond47ef9e2022-09-28 22:24:28 -040028 }, [query, isLoading, data, error]);
Adrien Béraud88a52442021-04-26 12:11:41 -040029
simond47ef9e2022-09-28 22:24:28 -040030 const handleChange = (event) => setQuery(event.target.value);
Adrien Béraud88a52442021-04-26 12:11:41 -040031
32 return (
simond47ef9e2022-09-28 22:24:28 -040033 <TextField
34 className="main-search-input"
35 type="search"
36 placeholder="Register a unique name"
37 error={!error}
38 label={
39 isLoading
40 ? 'Searching...'
41 : error && error !== 400
42 ? 'This name is available'
43 : data && data.address
44 ? 'This name is not available'
45 : ''
46 }
47 value={query}
48 disabled={props.disabled}
49 onChange={handleChange}
50 InputProps={{
51 startAdornment: (
52 <InputAdornment position="start">
53 <SearchRounded />
54 </InputAdornment>
55 ),
56 }}
57 />
58 );
Adrien Béraud88a52442021-04-26 12:11:41 -040059}