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/cd8776342240988652da17b5538c5bb5 to your computer and use it in GitHub Desktop.
Save DanyF-github/cd8776342240988652da17b5538c5bb5 to your computer and use it in GitHub Desktop.
// client/src/components/Homeworks/HomeworkForm.tsx
import { useMutation } from '@apollo/client';
import React, { useState } from 'react';
import { Homework } from '../../models';
import { ADD_HOMEWORK } from '../../data/mutations';
import { GET_HOMEWORKS } from '../../data/queries';
const HomeworkForm = () => {
// declare the state for the controlled form
const [description, setDescription] = useState('');
// setup the mutate function that creates the homework
const [addHomework] = useMutation<
{ saveHomework: Homework },
{ description: string }
>(ADD_HOMEWORK, {
// on completion, reset the state
onCompleted() {
setDescription('');
},
// after creating the homework, add it to the local cache
update(cache, { data }) {
const existingHomeworksData = cache.readQuery<{ homeworks: Homework[] }>({
query: GET_HOMEWORKS,
});
cache.writeQuery({
query: GET_HOMEWORKS,
data: {
homeworks: [
...(existingHomeworksData?.homeworks as Homework[]),
data?.saveHomework,
],
},
});
},
});
return (
<>
<form
className="form-inline"
onSubmit={(e) => {
// when submit the form call the mutate function
e.preventDefault();
description &&
addHomework({
variables: {
description,
},
});
}}
>
<label htmlFor="description">
Description
</label>
<input
type="text"
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<button type="submit">
Submit
</button>
</form>
</>
);
};
export default HomeworkForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment