😎 결과
2022-09-02.2.22.28.mov
🔗 참고 링크
배열 state 수정하기
💭 내 생각
처음에 댓글 crud rest api를 만들고 프론트 단을 완성했을 때, 속도가 매우매우 느렸다.
heroku가 느리다는 말이 있어서 그런가보다 했었는데,
나중에 생각해보니 굳이 db가 변경될 때까지 기다렸다가 get api를 남용할 필요가 없었다.
프론트에서 crud api를 한번 호출하고, 성공하면 state에서 바뀐 부분만 바로 수정하는 것으로 코드를 바꾸자 속도가 훨씬 많이 개선되었다.
🔑 작업과정
프론트
1. post
유저가 댓글을 입력하면, comments 배열 마지막에 새로운 댓글을 추가한다.
const [ comments , setComments ] = useState < CommentType [ ] > ( [ ] ) ;
const createComment = async ( e ) => {
e . preventDefault ( ) ;
const body = {
_forum : forumId ,
commentText : commentText
}
Comments . postComment ( body )
. then ( data => {
const newComment = data
const newComments = [ ...comments , newComment ] ; // 댓글 추가
setComments ( newComments )
setCommentText ( '' ) ;
} )
. catch ( err => {
setAlertShowMessage ( err . response . data ) ;
setAlertShow ( true ) ;
console . log ( err )
} )
}
2. update
유저가 댓글을 수정하면, findIndex 로 타겟 comment 를 찾아 commentText 만 바꿔준다.
const [ comments , setComments ] = useState < CommentType [ ] > ( [ ] ) ;
const updateComment = async ( ) => {
const body = {
commentText : commentText ,
}
Comments . updateComment ( body , targetId )
. then ( data => {
const newComents = [ ...comments ] ;
const newCommentText = data . commentText ;
const findIndex = newComents . findIndex ( el => el . commentId == targetId ) ;
if ( findIndex !== - 1 ) {
newComents [ findIndex ] = {
...newComents [ findIndex ] ,
commentText : newCommentText ,
} ;
setComments ( newComents )
setTargetId ( '' ) ;
}
} )
. catch ( err => {
console . log ( err ) ;
setAlertShowMessage ( err . response . data ) ;
setAlertShow ( true ) ;
} )
}
3. delete
유저가 댓글을 삭제하면, filter 로 타겟 comment 만 삭제한다.
const [ comments , setComments ] = useState < CommentType [ ] > ( [ ] ) ;
const deleteComment = async ( commentId : Types [ 'commentId' ] ) => {
const params = {
_forum : forumId
}
Comments . deleteComment ( params , commentId )
. then ( ( ) => {
const newComments = comments . filter ( comment => comment . commentId !== commentId ) ;
setComments ( newComments )
} )
. catch ( err => {
console . log ( err ) ;
} )
}
😎 결과
2022-09-02.2.22.28.mov
🔗 참고 링크
배열 state 수정하기
💭 내 생각
처음에 댓글 crud rest api를 만들고 프론트 단을 완성했을 때, 속도가 매우매우 느렸다.
heroku가 느리다는 말이 있어서 그런가보다 했었는데,
나중에 생각해보니 굳이 db가 변경될 때까지 기다렸다가 get api를 남용할 필요가 없었다.
프론트에서 crud api를 한번 호출하고, 성공하면 state에서 바뀐 부분만 바로 수정하는 것으로 코드를 바꾸자 속도가 훨씬 많이 개선되었다.
🔑 작업과정
프론트
1. post
유저가 댓글을 입력하면, comments 배열 마지막에 새로운 댓글을 추가한다.
2. update
유저가 댓글을 수정하면, findIndex 로 타겟 comment 를 찾아 commentText 만 바꿔준다.
3. delete
유저가 댓글을 삭제하면, filter 로 타겟 comment 만 삭제한다.