1- import { useEffect , useState , type FormEvent , type KeyboardEvent } from 'react' ;
1+ import { useEffect , useRef , useState , type FormEvent , type KeyboardEvent } from 'react' ;
22import { useNavigate , useParams } from 'react-router-dom' ;
33import { ApiError } from '../api/client' ;
44import { articlesApi } from '../api/services' ;
@@ -17,20 +17,33 @@ export function Editor() {
1717 const [ tagField , setTagField ] = useState ( '' ) ;
1818 const [ errors , setErrors ] = useState < Errors | null > ( null ) ;
1919 const [ isSubmitting , setIsSubmitting ] = useState ( false ) ;
20+ const userRef = useRef ( user ) ;
21+ userRef . current = user ;
2022
2123 useEffect ( ( ) => {
2224 if ( ! slug ) return ;
23- articlesApi . get ( slug ) . then ( ( { article } ) => {
24- if ( user && article . author . username !== user . username ) {
25- navigate ( '/' ) ;
26- return ;
27- }
28- setTitle ( article . title ) ;
29- setDescription ( article . description ) ;
30- setBody ( article . body ) ;
31- setTagList ( article . tagList ) ;
32- } ) ;
33- } , [ slug , user , navigate ] ) ;
25+ let cancelled = false ;
26+ articlesApi
27+ . get ( slug )
28+ . then ( ( { article } ) => {
29+ if ( cancelled ) return ;
30+ const currentUser = userRef . current ;
31+ if ( currentUser && article . author . username !== currentUser . username ) {
32+ navigate ( '/' ) ;
33+ return ;
34+ }
35+ setTitle ( article . title ) ;
36+ setDescription ( article . description ) ;
37+ setBody ( article . body ) ;
38+ setTagList ( article . tagList ) ;
39+ } )
40+ . catch ( ( ) => {
41+ if ( ! cancelled ) navigate ( '/' ) ;
42+ } ) ;
43+ return ( ) => {
44+ cancelled = true ;
45+ } ;
46+ } , [ slug , navigate ] ) ;
3447
3548 const addTag = ( ) => {
3649 const tag = tagField . trim ( ) ;
0 commit comments