1+ import React , { useRef } from 'react' ;
2+ import { useQuery , useMutation } from '@apollo/client' ;
3+ import { GET_BOOKS , ADD_BOOK } from './gql' ;
4+
5+ export default function Books ( ) {
6+ const bookTitle = useRef ( null ) ;
7+ const bookAuthor = useRef ( null ) ;
8+
9+ const { loading, error, data } = useQuery ( GET_BOOKS ) ;
10+ const [ addBook ] = useMutation ( ADD_BOOK , {
11+ update ( cache , { data : { addBook } } ) {
12+ const { books } : any = cache . readQuery ( { query : GET_BOOKS } ) ;
13+
14+ cache . writeQuery ( {
15+ query : GET_BOOKS ,
16+ data : {
17+ books : [ ...books , addBook ]
18+ }
19+ } ) ;
20+ }
21+ } ) ;
22+
23+ if ( loading ) return < p > Loading...</ p > ;
24+ if ( error ) return < p > Error :(</ p > ;
25+
26+ const handleSubmit = ( event ) => {
27+ event . preventDefault ( ) ;
28+
29+ addBook ( { variables : { title : event . target . title . value , author : event . target . author . value } } ) ;
30+
31+ event . target . title = '' ;
32+ event . target . author = '' ;
33+ }
34+
35+ return (
36+ < section >
37+ < ul >
38+ {
39+ data . books . map ( ( { title, author } ) => (
40+ < li key = { title } >
41+ { title } : { author }
42+ </ li >
43+ ) )
44+ }
45+ </ ul >
46+ < form onSubmit = { ( e ) => handleSubmit ( e ) } style = { { display :'flex' , flexDirection : 'row' } } >
47+ < label htmlFor = "title" > Title:</ label >
48+ < input type = "text" id = "title" name = "title" ref = { bookTitle } />
49+ < label htmlFor = "author" > Book:</ label >
50+ < input type = "text" id = "author" name = "author" ref = { bookAuthor } />
51+ < button type = "submit" > Submit</ button >
52+ </ form >
53+ </ section >
54+ ) ;
55+ }
0 commit comments