Skip to content

Commit 0dc323c

Browse files
committed
refac: editPostOnDb & addPostToDb functions
1 parent 8b06621 commit 0dc323c

4 files changed

Lines changed: 38 additions & 132 deletions

File tree

src/actions/actions.ts

Lines changed: 23 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -35,80 +35,11 @@ export async function addPostToDb(post: AddedPostToApi) {
3535
}
3636
}
3737

38-
export async function editPostOnDb() {
39-
console.log("executou editPostOnDb")
40-
}
41-
42-
const usernameSchema = z.string()
43-
44-
export async function setUsernameAction(username: unknown) {
45-
try {
46-
const validatedUsername = usernameSchema.safeParse(username)
47-
if (!validatedUsername.success) {
48-
return { error: true, errorMessage: "Invalid username." }
49-
}
50-
51-
return { username: validatedUsername.data }
52-
} catch {
53-
return {
54-
error: true,
55-
errorMessage: "Could not set username. Please, try again in a few minutes."
56-
}
57-
}
58-
}
59-
60-
// rename this file
61-
// move this file
62-
/*
63-
"use server"
64-
65-
import { z } from "zod"
66-
import { revalidatePath } from "next/cache"
67-
import { postFormSchema } from "@/lib/types"
68-
import { baseUrl, delay } from "@/lib/utils"
69-
70-
const addedPostToApiSchema = postFormSchema.extend({ username: z.string() })
71-
72-
export async function addPostAction(newPost: unknown) {
73-
const failMessage = { message: "Could not add post. Please, try again in a few minutes." }
74-
try {
75-
const validatedNewPost = addedPostToApiSchema.safeParse(newPost)
76-
if (!validatedNewPost.success) {
77-
return { message: "Invalid post data." }
78-
}
79-
80-
const response = await fetch(baseUrl, {
81-
method: "POST",
82-
headers: { "content-type": "application/json" },
83-
body: JSON.stringify(validatedNewPost.data)
84-
})
85-
86-
if (!response.ok) {
87-
return failMessage
88-
}
89-
90-
const data = await response.json()
91-
console.log("response:", response)
92-
console.log("data:", data)
93-
// at the time of this writing, a post object that wasn't created on db don't have these properties
94-
const postWasNotReallyCreatedOnDb = !data.id || !data.created_datetime
95-
if (postWasNotReallyCreatedOnDb) {
96-
console.log("postWasNotReallyCreatedOnDb:", postWasNotReallyCreatedOnDb)
97-
return failMessage
98-
}
99-
} catch {
100-
return failMessage
101-
}
102-
103-
revalidatePath("/feed", "layout")
104-
}
105-
10638
const postIdSchema = z.number()
10739

108-
export async function editPostAction(editedData: unknown, postId: unknown) {
109-
const failMessage = { message: "Could not edit post. Please, try again in a few minutes." }
40+
export async function editPostOnDb(editedData: unknown, postId: unknown) {
41+
const failMessage = "Could not edit post. Please, try again in a few minutes."
11042
try {
111-
await delay(1000)
11243
const validatedEditedData = postFormSchema.safeParse(editedData)
11344
const validatedPostId = postIdSchema.safeParse(postId)
11445
if (!validatedEditedData.success || !validatedPostId.success) {
@@ -122,37 +53,35 @@ export async function editPostAction(editedData: unknown, postId: unknown) {
12253
})
12354

12455
if (!response.ok) {
125-
return failMessage
56+
return { message: failMessage }
12657
}
58+
59+
const editedPostOnDb: unknown = await response.json()
60+
const validatedEditedPostOnDb = postSchema.safeParse(editedPostOnDb)
61+
if (!validatedEditedPostOnDb.success) {
62+
return { message: "Post was not edited on db" }
63+
}
64+
65+
return { editedPostOnDb: validatedEditedPostOnDb.data }
12766
} catch {
128-
return failMessage
67+
return { message: failMessage }
12968
}
130-
131-
revalidatePath("/feed", "layout")
13269
}
13370

134-
export async function deletePostAction(postId: unknown) {
135-
const failMessage = { message: "Could not delete post. Please, try again in a few minutes." }
71+
const usernameSchema = z.string()
72+
73+
export async function setUsernameAction(username: unknown) {
13674
try {
137-
await delay(1000)
138-
const validatedPostId = postIdSchema.safeParse(postId)
139-
if (!validatedPostId.success) {
140-
return { message: "Invalid post id." }
75+
const validatedUsername = usernameSchema.safeParse(username)
76+
if (!validatedUsername.success) {
77+
return { error: true, errorMessage: "Invalid username." }
14178
}
14279

143-
const response = await fetch(`${baseUrl}${validatedPostId.data}/`, {
144-
method: "DELETE",
145-
headers: { "content-type": "application/json" },
146-
body: JSON.stringify({})
147-
})
148-
149-
if (!response.ok) {
150-
return failMessage
151-
}
80+
return { username: validatedUsername.data }
15281
} catch {
153-
return failMessage
82+
return {
83+
error: true,
84+
errorMessage: "Could not set username. Please, try again in a few minutes."
85+
}
15486
}
155-
156-
revalidatePath("/feed", "layout")
15787
}
158-
*/

src/components/edit-post.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ export function EditPost({ postId }: PostIdProp) {
3838
</DialogHeader>
3939
<PostForm
4040
actionType="edit"
41-
onFormSubmission={() => flushSync(() => setIsDialogOpen(false))}
41+
closeDialog={() => flushSync(() => setIsDialogOpen(false))}
4242
/>
4343
</DialogContent>
4444
</Dialog>

src/components/post-form.tsx

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,12 @@ import { Input } from "@/components/ui/input"
88
import { Textarea } from "@/components/ui/textarea"
99
import { PostFormFooter } from "./post-form-footer"
1010
import { usePostsContext, useUsernameContext } from "@/lib/hooks"
11-
import { type ActionTypes, type PostFormType, postFormSchema } from "@/lib/types"
12-
import { addPostToDb } from "@/actions/actions"
13-
// import { type ActionTypes, type Post, type PostFormType, postFormSchema } from "@/lib/types"
14-
// import { createPostServerAction } from "@/actions/create-post-server-action"
11+
import { type ActionTypes, type PostFormType, type Post, postFormSchema } from "@/lib/types"
12+
import { addPostToDb, editPostOnDb } from "@/actions/actions"
1513

1614
type PostFormProps = {
1715
actionType: ActionTypes
18-
onFormSubmission?: () => void
16+
closeDialog?: () => void
1917
}
2018

2119
function PostFormHeading() {
@@ -24,12 +22,8 @@ function PostFormHeading() {
2422

2523
const emptyFormDataState = { title: "", content: "" }
2624

27-
// export function PostForm({ actionType, onFormSubmission }: PostFormProps) {
28-
// const { selectedPost, selectedPostId, editPostOnState } = usePostsContext()
29-
// const { register, trigger, setValue, getValues, formState: { errors } } = useForm<PostFormType>({
30-
31-
export function PostForm({ actionType, onFormSubmission }: PostFormProps) {
32-
const { addPostToState, selectedPost } = usePostsContext()
25+
export function PostForm({ actionType, closeDialog }: PostFormProps) {
26+
const { editPostOnState, addPostToState, selectedPost, selectedPostId } = usePostsContext()
3327
const { usernameState } = useUsernameContext()
3428
const { register, setValue, formState: { errors } } = useForm<PostFormType>({
3529
resolver: zodResolver(postFormSchema)
@@ -53,17 +47,22 @@ export function PostForm({ actionType, onFormSubmission }: PostFormProps) {
5347
content: formData.get("content") as string,
5448
username: formData.get("username") as string,
5549
}
50+
5651
if (actionType === "add") {
5752
const { createdPostOnDb, message } = await addPostToDb(post)
5853
if (!createdPostOnDb) {
5954
return alert(message)
6055
}
6156
addPostToState(createdPostOnDb)
6257
setFormDataState(emptyFormDataState)
63-
} else if (actionType === "edit" && onFormSubmission) {
64-
// await editPostOnDb()
65-
// editPostOnState(post, selectedPostId as Post["id"])
66-
// onFormSubmission()
58+
} else if (actionType === "edit" && closeDialog) {
59+
const editedData = { title: post.title, content: post.content }
60+
const { editedPostOnDb, message } = await editPostOnDb(editedData, selectedPostId)
61+
if (!editedPostOnDb) {
62+
return alert(message)
63+
}
64+
editPostOnState(editedData, selectedPostId as Post["id"])
65+
closeDialog()
6766
}
6867
}
6968

src/contexts/posts-context-provider.tsx

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -23,28 +23,6 @@ export const PostsContext = createContext<PostsContextType | null>(null)
2323

2424
export function PostsContextProvider({ data, children }: PostsContextProviderProps) {
2525
const [posts, setPosts] = useState(data)
26-
// const [optimisticPosts, setOptimisticPosts] = useOptimistic(data, (state, { action, payload }) => {
27-
// if (action === "add") {
28-
// const tempPostToOptimisticUi = {
29-
// ...payload,
30-
// id: Math.random(),
31-
// // temporary. only to user sees when it's created with optimistic UI
32-
// created_datetime: new Date().toISOString()
33-
// }
34-
// return [tempPostToOptimisticUi, ...state]
35-
// }
36-
37-
// if (action === "edit") {
38-
// return state.map((post) =>
39-
// post.id === payload.selectedPostId ? { ...post, ...payload.editedData } : post)
40-
// }
41-
42-
// if (action === "delete") {
43-
// return state.filter((post) => post.id !== payload.id)
44-
// }
45-
46-
// return state
47-
// })
4826
const [selectedPostId, setSelectedPostId] = useState<Post["id"] | null>(null)
4927

5028
const selectedPost = posts.find((post) => post.id === selectedPostId)

0 commit comments

Comments
 (0)