Last active
November 9, 2019 13:41
-
-
Save dhanushkac/32682eeca5ced1e583819ff24bfb0fa2 to your computer and use it in GitHub Desktop.
Check username validity by user input
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 React, { useState, useEffect } from "react"; | |
import "./styles.css"; | |
function CheckUsername({ url }) { | |
const [result, setResult] = useState(""); | |
const [data, setData] = useState(""); | |
const handleErrors = response => { | |
console.log(response); | |
if (!response.ok) throw Error(response.status); | |
return response; | |
}; | |
const check = (username, abortController) => { | |
const lastUrl = `${url}${username}`; | |
if (username && username.length < 4) { | |
setResult("Username must be at least 4 characters long"); | |
} else if (username) { | |
setResult(""); | |
fetch(lastUrl, { | |
signal: abortController.signal | |
}) | |
.then(handleErrors) | |
.then(res => res.json()) | |
.then( | |
data => { | |
if (abortController.signal.aborted) { | |
return; | |
} | |
if (!data.taken) { | |
setResult("Username is available"); | |
} else { | |
setResult("Username is not available"); | |
} | |
}, | |
_ => setResult("Bad username found!!!") | |
); | |
} else { | |
setResult(""); | |
} | |
}; | |
useEffect(() => { | |
const abortController = new AbortController(); | |
check(data, abortController); | |
return () => { | |
abortController.abort(); | |
}; | |
}, [data]); | |
const onChange = username => { | |
setData(username); | |
}; | |
return ( | |
<div className="container"> | |
<form> | |
<div className="title">Enter Username</div> | |
<input | |
className="input" | |
type="text" | |
onChange={e => onChange(e.target.value)} | |
/> | |
</form> | |
<p className="result">{result}</p> | |
</div> | |
); | |
} | |
export default CheckUsername; |
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 React from "react"; | |
import CheckUsername from "./CheckUsername"; | |
function App() { | |
const BASE_URL = | |
"https://hxj1tck8l1.execute-api.us-east-1.amazonaws.com/default/users/taken?username="; | |
return <CheckUsername url={BASE_URL} />; | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment