Skip to content

Instantly share code, notes, and snippets.

@DanyF-github
Created January 8, 2021 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanyF-github/84bd96de089422906373485e3bcd5940 to your computer and use it in GitHub Desktop.
Save DanyF-github/84bd96de089422906373485e3bcd5940 to your computer and use it in GitHub Desktop.
// client/src/components/Homeworks/PasswordlessLogin.tsx
import { useMutation } from '@apollo/client';
import React, { useState } from 'react';
import { VERIFY_REQUEST, CHECK_CODE } from '../../data/mutations';
// the component receives a custom onLogin function that runs after a student has successfullysuccesfully authenticated
const PasswordlessLogin = ({
onLogin,
}: {
onLogin: (token: String) => void;
}) => {
// setup the state for the controlled form
const [number, setNumber] = useState('');
const [code, setCode] = useState('');
const [requestId, setRequestId] = useState<string | null>(null);
// setup mutate functions for both request a verification and check the code
const [verifyRequest] = useMutation<{
verifyRequest: { requestId: string };
verifyRequestVars: { number: string };
}>(VERIFY_REQUEST, {
// after getting the request id add it to the state
onCompleted(data: { verifyRequest: { requestId: string } }) {
setRequestId(data.verifyRequest.requestId);
},
});
const [checkCode] = useMutation<{
checkCode: { token: string };
checkCodeVars: { requestId: string; code: string; number: string };
}>(CHECK_CODE, {
// after authenticating call the custom onLogin function
onCompleted(data: { checkCode: { token: string } }) {
if (data.checkCode.token) {
onLogin(data.checkCode.token);
}
},
});
return (
<>
<form
onSubmit={(e) => {
// on submit check the code
e.preventDefault();
number && code && requestId && checkCode({
variables: {
requestId,
code,
number
}
});
}}
>
<div className="form-row">
<div className="col">
<label htmlFor="number">Phone Number</label>
<input
type="text"
className="form-control"
id="number"
placeholder="Enter phone number"
value={number}
onChange={(e) => setNumber(e.target.value)}
/>
</div>
<div className="col">
<button
onClick={(e) => {
// when clicking this button initiate the verification
number &&
verifyRequest({
variables: {
number,
},
});
}}
>
Request code
</button>
</div>
</div>
{requestId && ( // only show the elements below if a requestId has been successfullysuccesfully returned by the server
<>
<div className="form-group">
<label htmlFor="code">Code</label>
<input
type="text"
className="form-control"
id="code"
placeholder="Enter one time code"
value={code}
onChange={(e) => setCode(e.target.value)}
/>
</div>
<button type="submit" className="btn btn-primary">
Submit
</button>
</>
)}
</form>
</>
);
};
export default PasswordlessLogin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment