From 2d9042235c26bbe1a4e8d3b33b4a3e811e16a187 Mon Sep 17 00:00:00 2001 From: Pau Costa Date: Mon, 12 Feb 2024 12:03:31 +0100 Subject: [PATCH] :sparkle: Users can now edit posts Signed-off-by: Pau Costa --- client/src/routes/newPost.tsx | 52 +++++++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/client/src/routes/newPost.tsx b/client/src/routes/newPost.tsx index f73333a..b8b1bd4 100644 --- a/client/src/routes/newPost.tsx +++ b/client/src/routes/newPost.tsx @@ -1,14 +1,28 @@ import { Box, Button, TextField, Typography } from "@mui/material"; import { useAppDispatch } from "../app/store"; -import React from "react"; -import { createPost } from "../app/postSlice"; -import { useNavigate } from "react-router-dom"; +import React, { useEffect } from "react"; +import { + createPost, + selectAPost, + updatePost, +} from "../app/postSlice"; +import { useNavigate, useParams } from "react-router-dom"; +import { useSelector } from "react-redux"; export default function NewPost() { + const { id } = useParams(); const dispatch = useAppDispatch(); const navigate = useNavigate(); const [newPostText, setNewPostText] = React.useState(""); const [newPostTitle, setNewPostTitle] = React.useState(""); + const aPost = useSelector(selectAPost); + + useEffect(() => { + if (id) { + setNewPostText(aPost.content); + setNewPostTitle(aPost.title); + } + }, [aPost, id]); const handleCreatePost = () => { if (newPostText === "" || newPostTitle === "") return; @@ -19,6 +33,16 @@ export default function NewPost() { navigate("/global"); }; + const handleUpdatePost = () => { + if (newPostText === "" || newPostTitle === "") return; + if (!id) return; + + dispatch(updatePost(parseInt(id), newPostTitle, newPostText)); + setNewPostText(""); + setNewPostTitle(""); + navigate("/global"); + }; + return ( - + {id ? ( + + ) : ( + + )} ); }