Created
March 31, 2023 01:59
-
-
Save ejangi/8228eb0c11d68e44bc1b89d67903726d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using a reducer allows you to control field validation etc | |
// without having a million useState(); calls and logic spanning across multiple functions. | |
import { useReducer } from "react"; | |
function EditCalendarEvent() { | |
const [event, updateEvent] = useReducer( | |
(prev, next) => { | |
const newEvent = { ...prev, ...next }; | |
// Ensure that the start date is never after the end date | |
if (newEvent.startDate > newEvent.endDate) { | |
newEvent.endDate = newEvent.startDate; | |
} | |
// Ensure that the title is never more than 100 chars | |
if (newEvent.title.length > 100) { | |
newEvent.title = newEvent.title.substring(0, 100); | |
} | |
return newEvent; | |
}, | |
{ title: "", description: "", attendees: [] } | |
); | |
return ( | |
<> | |
<input | |
value={event.title} | |
onChange={(e) => updateEvent({ title: e.target.value })} | |
/> | |
{/* ... */} | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment