43
loading...
This website collects cookies to deliver better user experience
useState()
hook along with Immer.// @src/App.jsx
import React, { useState } from "react";
const App = () => {
const [name, setName] = useState("");
const [list, setList] = useState([
{
id: Math.floor(Math.random() * 100),
title: "Cheongchun Blossom",
},
{
id: Math.floor(Math.random() * 100),
title: "Koe no Katachi",
},
{
id: Math.floor(Math.random() * 100),
title: "By Spring",
},
]);
const [isEdit, setIsEdit] = useState(false);
const [update, setUpdate] = useState({
id: null,
title: "",
});
const handleOnSubmit = (e) => {
e.preventDefault();
setList(
// Logic goes here
);
setName("");
};
const handleDelete = (id) => {
setList(
// Logic goes here
);
};
const handleOnPatch = () => {
setList(
// Logic goes here
);
setName("");
setIsEdit(false);
setUpdate({
id: null,
title: "",
});
};
const handleIsEdit = (manga) => {
setIsEdit(true);
setUpdate(manga);
};
return (
// Hidden for simplicity
);
};
export default App;
const handleOnSubmit = (e) => {
e.preventDefault();
setList(
// Logic goes here
);
};
const handleOnSubmit = (e) => {
e.preventDefault();
setList([...list, { id: Math.floor(Math.random() * 100), title: name }]);
};
produce()
function:import produce from "immer";
// Hidden for simplicity
const handleOnSubmit = (e) => {
e.preventDefault();
setList(
produce(() => {
// Logic goes here
})
);
};
produce()
function, we'll get our draft and then we'll add an element to our state, like this:const handleOnSubmit = (e) => {
e.preventDefault();
setList(
produce((draft) => {
draft.push({
id: Math.floor(Math.random() * 100),
title: name,
});
})
);
};
const handleDelete = (id) => {
setList(
produce((draft) => {
// Logic goes here
})
);
};
const handleDelete = (id) => {
setList(
produce((draft) => {
const i = draft.findIndex((el) => el.id === id);
// More logic goes here
})
);
};
const handleDelete = (id) => {
setList(
produce((draft) => {
const i = draft.findIndex((el) => el.id === id);
draft.splice(i, 1);
})
);
};
const handleOnPatch = () => {
setList(
produce((draft) => {
// Logic goes here
})
);
};
const handleOnPatch = () => {
setList(
produce((draft) => {
const manga = draft.find((el) => el.id === update.id);
// Logic goes here
})
);
};
const handleOnPatch = () => {
setList(
produce((draft) => {
const manga = draft.find((el) => el.id === update.id);
manga.title = update.title;
})
);
};