I’m trying to find the best way to create and update items in a list. So, I have a form with item fields and I have the idea to provide a function (update or create) depending on the mode I choose. For example, I click the edit button and set the “update” mode, or I click the “add new item” button and set the “create” mode. In this case I don’t need to add two identical components with different click handlers (one for update, one for create), I will just provide a click handler depending on the mode state.
What do you think about this implementation?
import {useState} from "react";
enum MODES {
view= "view",
update= "update",
create= "create",
}
const Page = () => {
const [mode, setMode] = useState<MODES>(MODES.view);
const [clickHandler, setClickHandler] = useState<() => void>();
const [item, setItem] = useState({});
const updateHandler = () => {};
const createHandler = () => {};
const setModeHandler = (mode: MODES) => {
switch (mode) {
case MODES.update: {
setItem(selectedItem);
setClickHandler(updateHandler);
} break;
case MODES.create: {
setItem({});
setClickHandler(createHandler);
} break;
default: {
} break;
}
}
return (
<div>
<div>
<button onClick={() => {setModeHandler(MODES.update)}}>update</button>
<button onClick={() => {setModeHandler(MODES.create)}}>create</button>
</div>
<ItemModal click={clickHandler} item={item} />
</div>
)
}
I attached the draft to better understand my question.
I would be glad to hear your opinion on this matter.
What do you think about this idea?
Is it okay or better to use to components with different handlers?