Created
September 3, 2021 17:57
-
-
Save gmwill934/fb6a9775cda60dfa2cb7e75fff212b59 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Link from "next/link"; | |
import { useRouter } from "next/router"; | |
import { useEffect, ChangeEvent, MouseEvent } from "react"; | |
import { useState } from "react"; | |
type TState = { | |
name?: string | string[]; | |
temperature?: string | string[]; | |
}; | |
export default function Slug() { | |
const router = useRouter(); | |
const [state, setState] = useState<TState>({ | |
name: "", | |
temperature: "", | |
}); | |
useEffect(() => { | |
Object.keys(router.query).forEach((obj) => { | |
if (!(router.query[obj] instanceof Array)) { | |
const key = obj; | |
const value = router.query[obj]; | |
setState((prevState) => ({ ...prevState, [key]: value })); | |
} | |
}); | |
}, [router.isReady]); | |
const canSubmit = !!!state.name || !!!state.temperature; | |
const onChange = (e: ChangeEvent<HTMLInputElement>) => { | |
setState((prevState) => ({ | |
...prevState, | |
[e.target.name]: e.target.value, | |
})); | |
router.push(`/question/?${[e.target.name]}=${e.target.value}`); | |
}; | |
const clear = (e: MouseEvent<HTMLButtonElement, globalThis.MouseEvent>) => { | |
e.preventDefault(); | |
setState({ name: "", temperature: "" }); | |
router.push("/question"); | |
}; | |
return ( | |
<> | |
<h2>Hello, {state.name || " can you please type your name?"}</h2> | |
<form> | |
<div className="input"> | |
<label htmlFor="name">Name</label> | |
<input | |
id="name" | |
name="name" | |
type="text" | |
value={state.name} | |
onChange={onChange} | |
placeholder="please enter your name" | |
/> | |
</div> | |
<div className="input"> | |
<label htmlFor="temperature">Temperature</label> | |
<input | |
id="temperature" | |
name="temperature" | |
type="text" | |
value={state.temperature} | |
onChange={onChange} | |
placeholder="please enter your temperature" | |
/> | |
</div> | |
<Link | |
href={{ pathname: "/question", query: { name: "", temperature: "" } }} | |
> | |
<button onClick={clear}>Clear Name</button> | |
</Link> | |
<button | |
type="submit" | |
disabled={canSubmit} | |
onClick={(e) => { | |
e.preventDefault(); | |
window.alert(JSON.stringify(state, null, 2)); | |
}} | |
> | |
Submit | |
</button> | |
</form> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment