11import React , { useRef } from 'react' ;
22import { useQuery , useMutation } from '@apollo/client' ;
33import { GET_BOOKS , ADD_BOOK } from './gql' ;
4+ import { Can } from '@casl/react' ;
5+ import ability from './ability' ;
6+ import { Author } from '../../rules/entities' ;
47
58export default function Books ( ) {
69 const bookTitle = useRef ( null ) ;
@@ -13,7 +16,7 @@ export default function Books() {
1316
1417 cache . writeQuery ( {
1518 query : GET_BOOKS ,
16- data : {
19+ data : {
1720 books : [ ...books , addBook ]
1821 }
1922 } ) ;
@@ -25,13 +28,16 @@ export default function Books() {
2528
2629 const handleSubmit = ( event ) => {
2730 event . preventDefault ( ) ;
28-
29- addBook ( { variables : { title : event . target . title . value , author : event . target . author . value } } ) ;
31+ const target = event . target ;
3032
31- event . target . title = '' ;
32- event . target . author = '' ;
33+ addBook ( { variables : { title : target . title . value , author : target . author . value } } ) ;
34+
35+ target . title . value = '' ;
36+ target . author . value = '' ;
3337 }
3438
39+ const author = new Author ( { isShowAuthor : data . books . length === 2 } ) ;
40+
3541 return (
3642 < section >
3743 < ul >
@@ -43,12 +49,17 @@ export default function Books() {
4349 ) )
4450 }
4551 </ ul >
46- < form onSubmit = { ( e ) => handleSubmit ( e ) } style = { { display :'flex' , flexDirection : 'row' } } >
52+ < form onSubmit = { ( e ) => handleSubmit ( e ) } style = { { display : 'flex' , flexDirection : 'row' } } >
4753 < label htmlFor = "title" > Title:</ label >
4854 < 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 >
55+
56+ < label htmlFor = "author" > Book:</ label >
57+ < input type = "text" id = "author" name = "author" ref = { bookAuthor } />
58+
59+ < Can I = "update" a = { author } ability = { ability } >
60+ { ( ) => < button type = "submit" > Submit</ button > }
61+ </ Can >
62+
5263 </ form >
5364 </ section >
5465 ) ;
0 commit comments