들어가기
CreateComment(1)에서 comment를 만들었다. 이제 realTime, 새로고침없이,
실시간으로 update될 수 있게 cache를 다룬다. 엄청 중요하고 어렵다.
newCacheComment는 않만들어도 되지만, 다음편에 deleteComment를 만들기
위해서 만들어 주는 것이다.
function Comments({ author, photoId, caption, commentNumber, comments }) {
const { data: userData } = useUser()
///1. me의 data를 받아오기 위해서, useUser() hook을 사용해서, me의 data를
///받아온다.
const { register, handleSubmit, setValue, getValues } = useForm()
const createCommentUpdate = (cache, result) => {
const { payload } = getValues() ///getValues()를 이용해서 payload를 받아온다.
setValue('payload', '') ///payload를 받아왔으면, 댓글다는 칸을 바운다(reset시킨다)
const {
data: {
createComment: { ok, id },
},
} = result ///createComment mutation을 샐행해서 return된 data(ok, id)를 받아온다.
///id는 server의 newComment의 id
if (ok && userData?.me) { ///result에서 ok와 useUser사용해서 받은 data에 me가
///있으면 다음부분 실행~
const newComment = {
__typename: 'Comment',
createdAt: Date.now() + '', ///createdAt은 string이기떄문에 + '' 붙여줌.
id,
isMine: true,
payload,
user: {
...userData.me,
},
///cache에 있는 Comment와 같은 모양으로 newComment를 만들어줌.
///Comment cache 모양은 밑에서 확인.
}
const newCacheComment = cache.writeFragment({
data: newComment,
fragment: gql`
fragment BSName on Comment {
id
createdAt
isMine
payload
user {
username
avatar
}
}
`,
})
///newCacheComment를 만들어서 cache에 newComment를 write해준다.
///햇갈리고 어려우면, 그냥 외운다.ㅜㅜ
///writeFragment한 후에 cache.modify해서 cache를 update해준다.
///newCacheComment를 만드는, cache를 write하는 이유는 deleteComment를 위해서임.
cache.modify({
id: `Photo:${photoId}`,
fields: {
comments(prev) {
return [...prev, newCacheComment]
},
commentNumber(prev) {
return prev + 1
},
},
})
///cache를 modify로 update하는데, Photo 를 update함.
///Photo아이디를 찾아서 fields를 지정해서 modify해서, Photo cache를
///update해준다.
}
}
const [createCommentMutaiton, { loading }] = useMutation(
CREATE_COMMENT_MUTATION,
{ update: createCommentUpdate }
)
const onValid = (data) => {
const { payload } = data
if (loading) {
return
}
createCommentMutaiton({
variables: {
photoId,
payload,
},
})
}
return (
***********************
<CommentsContainer>
<Comment author={author} payload={caption} />
<CommentCount>
{commentNumber === 1 ? '1 comment' : `${commentNumber} comments`}
</CommentCount>
{comments?.map((comment) => (
<Comment
key={comment.id}
author={comment.user.username}
payload={comment.payload}
id={comment.id}
photoId={photoId}
isMine={comment.isMine}
********************Comment Component에 보내주는 props확인할 것*******
/>
))}
<PostCommentContainer>
<form onSubmit={handleSubmit(onValid)}>
<PostCommentInput
{...register('payload', { required: true, minLength: 5 })}
type="text"
placeholder="Write a comment.."
/>
</form>
</PostCommentContainer>
</CommentsContainer>
)}
This article provides a solid overview of how to create comments in real time without needing to refresh the page, which is crucial for enhancing user experience. The use of the createCommentUpdate
function to manage the cache effectively shows a great understanding of React's capabilities.
The explanation about leveraging cache.writeFragment
and cache.modify
to keep the comment section updated is particularly useful. It's also nice to see how you're handling form submissions with useForm
, making the code cleaner and more efficient.
As a side note, integrating real-time features like this is essential for applications, especially for something as interactive as "Sprunki," where user engagement is key. Keep up the great work!
Great information! I will visit your site more bitlife often so I am updated. The ideas I gather from here cannot be paid with money. Thanks very much!