From 1dc07f39e5ee841065c8b09dc9c1fc79f46656fe Mon Sep 17 00:00:00 2001 From: Jason Zhu Date: Tue, 7 Mar 2023 00:06:41 +1100 Subject: [PATCH] 02_lesson: use prepare callback to customize the creation of the payload value --- .../src/features/posts/AddPostForm.js | 9 +-------- .../src/features/posts/postsSlice.js | 17 ++++++++++++++--- 2 files changed, 15 insertions(+), 11 deletions(-) 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, + }, + }; + }, }, }, });