From 83a42fd6607e654d28d4053fa89d6dcda744a337 Mon Sep 17 00:00:00 2001 From: Jason Zhu Date: Tue, 7 Mar 2023 13:12:54 +1100 Subject: [PATCH] 02_lesson: Added usersSlice and attach userid to post --- 02_lesson_starter/src/app/store.js | 3 ++- .../src/features/posts/AddPostForm.js | 24 ++++++++++++++++--- .../src/features/posts/PostsList.js | 1 + .../src/features/posts/postsSlice.js | 4 +++- .../src/features/users/usersSlice.js | 17 +++++++++++++ 5 files changed, 44 insertions(+), 5 deletions(-) create mode 100644 02_lesson_starter/src/features/users/usersSlice.js diff --git a/02_lesson_starter/src/app/store.js b/02_lesson_starter/src/app/store.js index 972e003..e4e9140 100644 --- a/02_lesson_starter/src/app/store.js +++ b/02_lesson_starter/src/app/store.js @@ -1,6 +1,7 @@ import { configureStore } from "@reduxjs/toolkit"; import postsReducer from "../features/posts/postsSlice"; +import usersReducer from "../features/users/usersSlice"; export const store = configureStore({ - reducer: { posts: postsReducer }, + reducer: { posts: postsReducer, users: usersReducer }, }); diff --git a/02_lesson_starter/src/features/posts/AddPostForm.js b/02_lesson_starter/src/features/posts/AddPostForm.js index a594f8f..02b5258 100644 --- a/02_lesson_starter/src/features/posts/AddPostForm.js +++ b/02_lesson_starter/src/features/posts/AddPostForm.js @@ -1,23 +1,36 @@ import { useState } from "react"; import { postAdded } from "./postsSlice"; -import { useDispatch } from "react-redux"; +import { useDispatch, useSelector } from "react-redux"; + +import { selectAllUsers } from "../users/usersSlice"; const AddPostForm = () => { + const dispatch = useDispatch(); + const [title, setTitle] = useState(""); // Temporary state for adding information in form const [content, setContent] = useState(""); - const dispatch = useDispatch(); + const [userId, setUserId] = useState(""); + + const users = useSelector(selectAllUsers); // get users from Redux store const onTitleChanged = (e) => setTitle(e.target.value); const onContentChanged = (e) => setContent(e.target.value); + const onAuthorChanged = (e) => setUserId(e.target.value); const onSavePostClicked = () => { if (title && content) { - dispatch(postAdded(title, content)); + dispatch(postAdded(title, content, userId)); setTitle(""); setContent(""); } }; + const usersOptions = users.map((user) => ( + + )); + return (

Add a New Post

@@ -30,6 +43,11 @@ const AddPostForm = () => { value={title} onChange={onTitleChanged} /> + +