-
-
Save DanyF-github/cd8776342240988652da17b5538c5bb5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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