02_lesson: use prepare callback to customize the creation of the payload value

02_lesson
Jason Zhu 2023-03-07 00:06:41 +11:00
parent 1e7c085d70
commit 1dc07f39e5
2 changed files with 15 additions and 11 deletions

View File

@ -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("");
}

View File

@ -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,
},
};
},
},
},
});