diff --git a/02_lesson_starter/src/features/posts/AddPostForm.js b/02_lesson_starter/src/features/posts/AddPostForm.js index 30174e1..a594f8f 100644 --- a/02_lesson_starter/src/features/posts/AddPostForm.js +++ b/02_lesson_starter/src/features/posts/AddPostForm.js @@ -1,5 +1,4 @@ import { useState } from "react"; -import { nanoid } from "@reduxjs/toolkit"; import { postAdded } from "./postsSlice"; import { useDispatch } from "react-redux"; @@ -13,13 +12,7 @@ const AddPostForm = () => { const onSavePostClicked = () => { if (title && content) { - dispatch( - postAdded({ - id: nanoid(), - title, - content, - }) - ); + dispatch(postAdded(title, content)); setTitle(""); setContent(""); } diff --git a/02_lesson_starter/src/features/posts/postsSlice.js b/02_lesson_starter/src/features/posts/postsSlice.js index 6869183..ebe65f3 100644 --- a/02_lesson_starter/src/features/posts/postsSlice.js +++ b/02_lesson_starter/src/features/posts/postsSlice.js @@ -1,4 +1,4 @@ -import { createSlice } from "@reduxjs/toolkit"; +import { createSlice, nanoid } from "@reduxjs/toolkit"; const initialState = [ { @@ -17,8 +17,19 @@ const postsSlice = createSlice({ name: "posts", initialState, reducers: { - postAdded(state, action) { - state.push(action.payload); // immer.js add new payload without mutation + postAdded: { + reducer: (state, action) => { + state.push(action.payload); + }, + prepare(title, content) { + return { + payload: { + id: nanoid(), + title, + content, + }, + }; + }, }, }, });