From 1e7c085d70e62aad8325f6f34573a8913d971f05 Mon Sep 17 00:00:00 2001 From: Jason Zhu Date: Mon, 6 Mar 2023 23:57:28 +1100 Subject: [PATCH] 02_lesson: created AddPostForm component --- 02_lesson_starter/src/App.js | 2 + .../src/features/posts/AddPostForm.js | 55 +++++++++++++++++++ .../src/features/posts/postsSlice.js | 8 ++- 3 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 02_lesson_starter/src/features/posts/AddPostForm.js diff --git a/02_lesson_starter/src/App.js b/02_lesson_starter/src/App.js index 06a69ae..e3a7b79 100644 --- a/02_lesson_starter/src/App.js +++ b/02_lesson_starter/src/App.js @@ -1,8 +1,10 @@ import PostsList from "./features/posts/PostsList"; +import AddPostForm from "./features/posts/AddPostForm"; function App() { return (
+
); diff --git a/02_lesson_starter/src/features/posts/AddPostForm.js b/02_lesson_starter/src/features/posts/AddPostForm.js new file mode 100644 index 0000000..30174e1 --- /dev/null +++ b/02_lesson_starter/src/features/posts/AddPostForm.js @@ -0,0 +1,55 @@ +import { useState } from "react"; +import { nanoid } from "@reduxjs/toolkit"; +import { postAdded } from "./postsSlice"; +import { useDispatch } from "react-redux"; + +const AddPostForm = () => { + const [title, setTitle] = useState(""); // Temporary state for adding information in form + const [content, setContent] = useState(""); + const dispatch = useDispatch(); + + const onTitleChanged = (e) => setTitle(e.target.value); + const onContentChanged = (e) => setContent(e.target.value); + + const onSavePostClicked = () => { + if (title && content) { + dispatch( + postAdded({ + id: nanoid(), + title, + content, + }) + ); + setTitle(""); + setContent(""); + } + }; + + return ( +
+

Add a New Post

+
+ + + +