02_lesson: use prepare callback to customize the creation of the payload value
parent
1e7c085d70
commit
1dc07f39e5
|
@ -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("");
|
||||
}
|
||||
|
|
|
@ -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,
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
|
Loading…
Reference in New Issue