Skip to content

Instantly share code, notes, and snippets.

@ejangi
Created March 31, 2023 01:59
Show Gist options
  • Save ejangi/8228eb0c11d68e44bc1b89d67903726d to your computer and use it in GitHub Desktop.
Save ejangi/8228eb0c11d68e44bc1b89d67903726d to your computer and use it in GitHub Desktop.
// 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