02_lesson: created AddPostForm component
parent
0ea7837958
commit
1e7c085d70
|
@ -1,8 +1,10 @@
|
|||
import PostsList from "./features/posts/PostsList";
|
||||
import AddPostForm from "./features/posts/AddPostForm";
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<main className="App">
|
||||
<AddPostForm />
|
||||
<PostsList />
|
||||
</main>
|
||||
);
|
||||
|
|
|
@ -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 (
|
||||
<section>
|
||||
<h2>Add a New Post</h2>
|
||||
<form>
|
||||
<label htmlFor="postTitle">Post Title:</label>
|
||||
<input
|
||||
type="text"
|
||||
id="postTitle"
|
||||
name="postTitle"
|
||||
value={title}
|
||||
onChange={onTitleChanged}
|
||||
/>
|
||||
<label htmlFor="postContent">Content:</label>
|
||||
<textarea
|
||||
id="postContent"
|
||||
name="postContent"
|
||||
value={content}
|
||||
onChange={onContentChanged}
|
||||
/>
|
||||
<button type="button" onClick={onSavePostClicked}>
|
||||
Save Post
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddPostForm;
|
|
@ -16,9 +16,15 @@ const initialState = [
|
|||
const postsSlice = createSlice({
|
||||
name: "posts",
|
||||
initialState,
|
||||
reducers: {},
|
||||
reducers: {
|
||||
postAdded(state, action) {
|
||||
state.push(action.payload); // immer.js add new payload without mutation
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const selectAllPosts = (state) => state.posts;
|
||||
|
||||
export const { postAdded } = postsSlice.actions;
|
||||
|
||||
export default postsSlice.reducer;
|
||||
|
|
Loading…
Reference in New Issue