Skip to content

Commit

Permalink
feat: post comment
Browse files Browse the repository at this point in the history
  • Loading branch information
laoriy committed Dec 22, 2023
1 parent 65f5e8a commit 831377a
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 12 deletions.
31 changes: 31 additions & 0 deletions 3.vue/5.server-render/nuxt-realworld/hooks/useComment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {
getCommentsFromArticle,
type ArticleComment,
postComment,
} from "~/service/comment"

function useComment(slug: string) {
const comments = ref<ArticleComment[]>([])
const comment = ref("")

const getComment = async (watching = false) => {
const { data } = await getCommentsFromArticle(slug)

comments.value = data.value?.comments || []
watching &&
watch(data, (newData) => {
comments.value = newData?.comments || []
})
}

const handlePostComment = async (body: string) => {
if (!body) return
await postComment(slug, body.trim())
getComment()
comment.value = ""
}

return { comments, comment, getComment, handlePostComment }
}

export default useComment
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
<template>
<form v-if="userInfo" class="card comment-form">
<form
v-if="userInfo"
class="card comment-form"
@submit.prevent="handlePostComment(comment)"
>
<div class="card-block">
<textarea
v-model="comment"
class="form-control"
placeholder="Write a comment..."
rows="3"
Expand Down Expand Up @@ -40,8 +45,7 @@
</template>

<script setup lang="ts">
import type { Author } from "~/service/article"
import { type ArticleComment, getCommentsFromArticle } from "~/service/comment"
import useComment from "~/hooks/useComment"
const props = defineProps({
slug: {
Expand All @@ -50,15 +54,13 @@ const props = defineProps({
},
})
const comments = ref<ArticleComment[]>([])
const { userInfo } = userStore()
const { comments, comment, handlePostComment, getComment } = useComment(
props.slug
)
const { data } = await getCommentsFromArticle(props.slug)
comments.value = data.value?.comments || []
const { userInfo } = userStore()
watch(data, (newData) => {
comments.value = newData?.comments || []
})
getComment(true)
</script>

<style scoped></style>
14 changes: 12 additions & 2 deletions 3.vue/5.server-render/nuxt-realworld/service/comment.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Author } from './article'
import type { Author } from "./article"

type ArticleComment = {
id: string
Expand All @@ -14,5 +14,15 @@ function getCommentsFromArticle(slug: string) {
})
}

export { getCommentsFromArticle }
function postComment(slug: string, body: string) {
return post(`/articles/${slug}/comments`, {
body: {
comment: {
body,
},
},
})
}

export { getCommentsFromArticle, postComment }
export type { ArticleComment }

0 comments on commit 831377a

Please sign in to comment.