Veikedo

Untitled

Jun 29th, 2017
499
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export type State = {
  2.     inputUrl: string;
  3.     shortenedUrl: string;
  4. };
  5.  
  6. export class UrlShortener extends React.Component<{}, State> {
  7.     constructor(props: {}, context: any) {
  8.         super(props, context);
  9.         this.state = {
  10.             inputUrl: "",
  11.             shortenedUrl: ""
  12.         };
  13.     }
  14.  
  15.     handleSubmit = async () => {
  16.         try {
  17.             const response = await fetch(`/url/${this.state.inputUrl}`, { method: "POST" });
  18.             const shortenedUrl = await response.json();
  19.             this.setState({ shortenedUrl });
  20.         } catch (error) {
  21.             alert("An error occurred!");
  22.         }
  23.     };
  24.  
  25.     handleChange = (e) => {
  26.         this.setState({
  27.             [e.target.name]: e.target.value
  28.         });
  29.     };
  30.  
  31.     render() {
  32.         const { inputUrl, shortenedUrl } = this.state;
  33.         return (
  34.             <form onSubmit={this.handleSubmit}>
  35.                 <input
  36.                     type="text"
  37.                     value={inputUrl}
  38.                     onChange={this.handleChange}
  39.                     name="inputUrl"
  40.                 />
  41.                 <input
  42.                     type="text"
  43.                     readOnly
  44.                     value={shortenedUrl}
  45.                 />
  46.             </form>
  47.         );
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment