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 { useState } from "react";
|
||||||
import { nanoid } from "@reduxjs/toolkit";
|
|
||||||
import { postAdded } from "./postsSlice";
|
import { postAdded } from "./postsSlice";
|
||||||
import { useDispatch } from "react-redux";
|
import { useDispatch } from "react-redux";
|
||||||
|
|
||||||
|
@ -13,13 +12,7 @@ const AddPostForm = () => {
|
||||||
|
|
||||||
const onSavePostClicked = () => {
|
const onSavePostClicked = () => {
|
||||||
if (title && content) {
|
if (title && content) {
|
||||||
dispatch(
|
dispatch(postAdded(title, content));
|
||||||
postAdded({
|
|
||||||
id: nanoid(),
|
|
||||||
title,
|
|
||||||
content,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
setTitle("");
|
setTitle("");
|
||||||
setContent("");
|
setContent("");
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
import { createSlice } from "@reduxjs/toolkit";
|
import { createSlice, nanoid } from "@reduxjs/toolkit";
|
||||||
|
|
||||||
const initialState = [
|
const initialState = [
|
||||||
{
|
{
|
||||||
|
@ -17,8 +17,19 @@ const postsSlice = createSlice({
|
||||||
name: "posts",
|
name: "posts",
|
||||||
initialState,
|
initialState,
|
||||||
reducers: {
|
reducers: {
|
||||||
postAdded(state, action) {
|
postAdded: {
|
||||||
state.push(action.payload); // immer.js add new payload without mutation
|
reducer: (state, action) => {
|
||||||
|
state.push(action.payload);
|
||||||
|
},
|
||||||
|
prepare(title, content) {
|
||||||
|
return {
|
||||||
|
payload: {
|
||||||
|
id: nanoid(),
|
||||||
|
title,
|
||||||
|
content,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
Loading…
Reference in New Issue