diff --git a/client/src/app/postSlice.ts b/client/src/app/postSlice.ts index c298498..cc7f733 100644 --- a/client/src/app/postSlice.ts +++ b/client/src/app/postSlice.ts @@ -95,6 +95,17 @@ export const commentAPost = dispatch(fetchAPost(postId)); dispatch(setStatus(Status.idle)); }; + +export const createPost = + (title: string, content: string): AppThunk => + async (dispatch: any) => { + const postApi = createApi(store); + + dispatch(setStatus(Status.loading)); + await postApi.createPost({ title, content }); + dispatch(fetchGlobalPosts()); + dispatch(setStatus(Status.idle)); + }; export const { setFollowedPosts, setGlobalPosts, setStatus, setAPost } = postSlice.actions; diff --git a/client/src/routes/newPost.tsx b/client/src/routes/newPost.tsx index 46ac5ce..f73333a 100644 --- a/client/src/routes/newPost.tsx +++ b/client/src/routes/newPost.tsx @@ -1,3 +1,53 @@ +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"; + export default function NewPost() { - return <>New Post; + const dispatch = useAppDispatch(); + const navigate = useNavigate(); + const [newPostText, setNewPostText] = React.useState(""); + const [newPostTitle, setNewPostTitle] = React.useState(""); + + const handleCreatePost = () => { + if (newPostText === "" || newPostTitle === "") return; + + dispatch(createPost(newPostTitle, newPostText)); + setNewPostText(""); + setNewPostTitle(""); + navigate("/global"); + }; + + return ( + + + Share your thoughts! + + setNewPostTitle(e.target.value)} + sx={{ marginBottom: 2 }} + /> + setNewPostText(e.target.value)} + multiline + rows={4} + sx={{ marginBottom: 2 }} + /> + + + ); } diff --git a/client/src/routes/postList.tsx b/client/src/routes/postList.tsx index 660406c..6e568dd 100644 --- a/client/src/routes/postList.tsx +++ b/client/src/routes/postList.tsx @@ -30,7 +30,19 @@ export default function PostList(props: PostListProps) { }, []); useEffect(() => { - setPosts(props.type === "all" ? globalPosts : followedPosts); + const postsToDisplay = props.type === "all" ? globalPosts : followedPosts; + let sortedPosts: Post[] = []; + + if (postsToDisplay.length > 0) { + sortedPosts = [...postsToDisplay].sort((a: Post, b: Post) => { + return b.createdAt! > a.createdAt! + ? 1 + : b.createdAt! < a.createdAt! + ? -1 + : 0; + }); + } + setPosts(sortedPosts); }, [followedPosts, globalPosts, props.type]); return (