Optimal way to reuse a modal for create and edit. Eg - create task and edit task.
I'm using react + react query and I keep finding myself creating several modals without much reusing of components. Upon refactoring my code a bunch, I am currently doing the following -
For the purpose of the example, let us take 2 modals - one for creating a task and one for editing a task. Let's say tasks only have 2 fields - title and due date.
What I currently do is -
1. create a context which has value = { title, setTitle, dueDate, setDueDate, createNewTask, updateTask }. The context also takes in as a prop where it sets the initial values for title and dueDate if a task was passed in. So if the context is being used for a new task, no task is passed in and the initial values for the states are default but if the context is being used for editing a task, its values are used as initial states.
2. I create components for Title and DueDate which use the context for their values and setter functions.
3. For the new task modal, I create a modal which has the Title and DueDate components and when the user clicks the 'Create' button, I call the createNewTask function from the context which handles the creation of the task.
4. For the edit task modal, I create a modal which has the same Title and DueDate components and when the user exits the modal (there is no update/save button), I call the updateTask function from the context which handles the update of the task.
Does this structure make sense? I end up reusing the individual components and the context stores state whether it is a new task or a task that is being updated. Depending on which is taking place, I call the function that makes sense.
0 Replies