Mirror: The highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.
at main 2.6 kB view raw
1import React from 'react'; 2import { gql, useMutation } from 'urql'; 3 4const LOGIN_MUTATION = gql` 5 mutation Login($input: LoginInput!) { 6 signin(input: $input) { 7 refreshToken 8 token 9 } 10 } 11`; 12 13const REGISTER_MUTATION = gql` 14 mutation Register($input: LoginInput!) { 15 register(input: $input) { 16 refreshToken 17 token 18 } 19 } 20`; 21 22const LoginForm = ({ onLoginSuccess }) => { 23 const [loginResult, login] = useMutation(LOGIN_MUTATION); 24 const [registerResult, register] = useMutation(REGISTER_MUTATION); 25 26 const onSubmitLogin = event => { 27 event.preventDefault(); 28 const data = new FormData(event.target); 29 const username = data.get('username'); 30 const password = data.get('password'); 31 32 login({ input: { username, password } }).then(result => { 33 if (!result.error && result.data && result.data.signin) { 34 onLoginSuccess(result.data.signin); 35 } 36 }); 37 }; 38 39 const onSubmitRegister = event => { 40 event.preventDefault(); 41 const data = new FormData(event.target); 42 const username = data.get('username'); 43 const password = data.get('password'); 44 45 register({ input: { username, password } }).then(result => { 46 if (!result.error && result.data && result.data.register) { 47 onLoginSuccess(result.data.register); 48 } 49 }); 50 }; 51 52 const disabled = loginResult.fetching || registerResult.fetching; 53 54 return ( 55 <> 56 <form onSubmit={onSubmitLogin}> 57 {loginResult.fetching ? <p>Logging in...</p> : null} 58 {loginResult.error ? <p>Oh no... {loginResult.error.message}</p> : null} 59 60 <fieldset disabled={disabled ? 'disabled' : null}> 61 <h3>Login</h3> 62 <label> 63 Username: 64 <input name="username" type="text" /> 65 </label> 66 67 <label> 68 Password: 69 <input name="password" type="password" /> 70 </label> 71 72 <button type="submit">Login</button> 73 </fieldset> 74 </form> 75 76 <form onSubmit={onSubmitRegister}> 77 {registerResult.fetching ? <p>Signing up...</p> : null} 78 {registerResult.error ? ( 79 <p>Oh no... {registerResult.error.message}</p> 80 ) : null} 81 82 <fieldset disabled={disabled ? 'disabled' : null}> 83 <h3>Register</h3> 84 <label> 85 {'Username: '} 86 <input name="username" type="text" /> 87 </label> 88 89 <label> 90 {'Password: '} 91 <input name="password" type="password" /> 92 </label> 93 94 <button type="submit">Register</button> 95 </fieldset> 96 </form> 97 </> 98 ); 99}; 100 101export default LoginForm;