@@ -2,8 +2,10 @@ import { useEffect, useState } from 'react';
2
2
import axios from 'axios' ;
3
3
import { useHistory , useParams } from 'react-router' ;
4
4
import propTypes from 'prop-types' ;
5
+ import useToast from '../hooks/toast' ;
6
+ import LoadingSpinner from './LoadingSpinner' ;
5
7
6
- const BlogForm = ( { editing, addToast } ) => {
8
+ const BlogForm = ( { editing } ) => {
7
9
const history = useHistory ( ) ;
8
10
const { id } = useParams ( ) ;
9
11
@@ -15,6 +17,9 @@ const BlogForm = ({ editing, addToast }) => {
15
17
const [ originalPublish , setOriginalPublish ] = useState ( false ) ;
16
18
const [ titleError , setTitleError ] = useState ( false ) ;
17
19
const [ bodyError , setBodyError ] = useState ( false ) ;
20
+ const [ loading , setLoading ] = useState ( true ) ;
21
+ const [ error , setError ] = useState ( '' ) ;
22
+ const { addToast } = useToast ( ) ;
18
23
19
24
useEffect ( ( ) => {
20
25
if ( editing ) {
@@ -25,7 +30,17 @@ const BlogForm = ({ editing, addToast }) => {
25
30
setOriginalBody ( res . data . body ) ;
26
31
setPublish ( res . data . publish ) ;
27
32
setOriginalPublish ( res . data . publish ) ;
33
+ setLoading ( false ) ;
34
+ } ) . catch ( e => {
35
+ setError ( 'something went wrong in db' ) ;
36
+ addToast ( {
37
+ type : 'danger' ,
38
+ text : 'something went wrong in db'
39
+ } )
40
+ setLoading ( false ) ;
28
41
} )
42
+ } else {
43
+ setLoading ( false ) ;
29
44
}
30
45
} , [ id , editing ] ) ;
31
46
@@ -71,6 +86,11 @@ const BlogForm = ({ editing, addToast }) => {
71
86
} ) . then ( res => {
72
87
console . log ( res ) ;
73
88
history . push ( `/blogs/${ id } ` )
89
+ } ) . catch ( e => {
90
+ addToast ( {
91
+ type : 'danger' ,
92
+ text : 'We could not update blog'
93
+ } )
74
94
} )
75
95
} else {
76
96
axios . post ( 'http://localhost:3001/posts' , {
@@ -84,6 +104,11 @@ const BlogForm = ({ editing, addToast }) => {
84
104
text : 'Successfully created!'
85
105
} ) ;
86
106
history . push ( '/admin' ) ;
107
+ } ) . catch ( e => {
108
+ addToast ( {
109
+ type : 'danger' ,
110
+ text : 'We could not create blog'
111
+ } )
87
112
} )
88
113
}
89
114
}
@@ -93,6 +118,14 @@ const BlogForm = ({ editing, addToast }) => {
93
118
setPublish ( e . target . checked ) ;
94
119
} ;
95
120
121
+ if ( loading ) {
122
+ return < LoadingSpinner />
123
+ }
124
+
125
+ if ( error ) {
126
+ return ( < div > { error } </ div > )
127
+ }
128
+
96
129
return (
97
130
< div >
98
131
< h1 > { editing ? 'Edit' : 'Create' } a blog post</ h1 >
0 commit comments