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/11cac022c8517b09204002f918d41542 to your computer and use it in GitHub Desktop.
Save DanyF-github/11cac022c8517b09204002f918d41542 to your computer and use it in GitHub Desktop.
// client/src/components/Students/StudentForm.tsx
import { useMutation } from '@apollo/client';
import React, { useState } from 'react';
import { ADD_STUDENT } from '../../data/mutations';
import { GET_STUDENTS } from '../../data/queries';
import { Student, StudentData, StudentVars } from '../../models';
const StudentForm = () => {
// set the state for the form
const [phoneNumber, setPhoneNumber] = useState('');
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
// create the mutate function for adding student
const [addStudent] = useMutation<{ saveStudent: Student }, StudentVars>(
ADD_STUDENT,
{
onCompleted() { // set the onCompleted function to reset the state
setPhoneNumber('');
setFirstName('');
setLastName('');
},
update(cache, { data }) { // set the update function to update local cache
const existingStudentsdata = cache.readQuery<StudentData>({
query: GET_STUDENTS,
});
cache.writeQuery({
query: GET_STUDENTS,
data: {
students: [
...(existingStudentsdata?.students as Student[]),
data?.saveStudent,
],
},
});
},
}
);
// render the form
return (
<form
className="form-inline"
onSubmit={(e) => {
e.preventDefault();
phoneNumber &&
firstName &&
lastName &&
addStudent({
variables: {
phoneNumber,
firstName,
lastName,
},
});
}}
>
<label htmlFor="phone">
Phone Number
</label>
<input
type="text"
id="phone"
name="phone"
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value)}
/>
<label htmlFor="firstName">
First Name
</label>
<input
type="text"
id="firstName"
name="firstName"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>
<label htmlFor="lastName">
Last Name
</label>
<input
type="text"
id="lastName"
name="lastName"
value={lastName}
onChange={(e) => setLastName(e.target.value)}
/>
<button type="submit">
Submit
</button>
</form>
);
};
export default StudentForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment