1
- import React , { useState } from "react" ;
2
- import { useHistory , Link } from "react-router-dom" ;
1
+ import React , { useState , useEffect } from "react" ;
2
+ import { useHistory , Link , useParams } from "react-router-dom" ;
3
3
import { FiArrowLeft } from 'react-icons/fi' ;
4
4
5
5
import './styles.css' ;
@@ -10,17 +10,44 @@ import api from "../../services/api";
10
10
11
11
export default function NewBook ( ) {
12
12
13
- const [ id , setPassword ] = useState ( null ) ;
13
+ const [ id , setId ] = useState ( null ) ;
14
14
const [ author , setAuthor ] = useState ( '' ) ;
15
15
const [ launchDate , setLaunchDate ] = useState ( '' ) ;
16
16
const [ price , setPrice ] = useState ( '' ) ;
17
17
const [ title , setTitle ] = useState ( '' ) ;
18
18
19
+ const { bookId} = useParams ( ) ;
20
+
19
21
const username = localStorage . getItem ( 'username' ) ;
20
22
const accessToken = localStorage . getItem ( 'accessToken' ) ;
21
23
22
24
const history = useHistory ( ) ;
23
25
26
+ async function loadBook ( ) {
27
+ try {
28
+ const response = await api . get ( `api/book/v1/${ bookId } ` , {
29
+ headers : {
30
+ Authorization : `Bearer ${ accessToken } `
31
+ }
32
+ } )
33
+ let adjustedDate = response . data . launchDate . split ( "T" , 10 ) [ 0 ] ;
34
+
35
+ setId ( response . data . id ) ;
36
+ setTitle ( response . data . title ) ;
37
+ setAuthor ( response . data . author ) ;
38
+ setPrice ( response . data . price ) ;
39
+ setLaunchDate ( adjustedDate )
40
+ } catch ( error ) {
41
+ alert ( 'Error recovering book! Try again' )
42
+ history . push ( '/books' ) ;
43
+ }
44
+ }
45
+
46
+ useEffect ( ( ) => {
47
+ if ( bookId === '0' ) return ;
48
+ else loadBook ( ) ;
49
+ } )
50
+
24
51
async function createNewBook ( e ) {
25
52
e . preventDefault ( ) ;
26
53
@@ -57,7 +84,7 @@ export default function NewBook(){
57
84
< section className = "form" >
58
85
< img src = { logo } alt = "Ntt" />
59
86
< h1 > Add New Book</ h1 >
60
- < p > Enter the book information and click 'Add' !</ p >
87
+ < p > Enter the book information and click 'Add' ! ### { bookId } </ p >
61
88
< Link className = "back-link" to = "/books" >
62
89
< FiArrowLeft size = { 16 } color = "#251fc5" />
63
90
Home
0 commit comments