export function useObjectState<T>(initialValue: T): [T, (c: Partial<T>) => any] { const [item, setItem] = useState<T>(initialValue); const handleChange = (changes: Partial<T>) => setItem(existing => ({ ...existing, ...changes })); return [item, handleChange]; } // Example use: const [item, handleChange] = useObjectState<ITransporterNotification>(props.item); <div> <Input placeholder="Omschrijving" value={item.description} onChange={(e) => handleChange({ description: e.target.value })} /> </div> <div> <DatePicker defaultValue={getDayJs(item.showFrom)} onChange={(d, s) => handleChange({ showFrom: s })} /> </div>
Without hook:
export function EditAbsencePopup(props: { calendar: ICalendar, calendarEvent: ICalendarEvent, closeFn: () => void, date: Date }) { const { calendar, calendarEvent, closeFn, date } = props; const [state, setState] = useState<Partial<ICalendarOverride>>({}); const updateState = (newState: Partial<ICalendarOverride>) => setState(oldState => {...oldState, ...newState}); // ... useEffect(() => { updateState({ hideOtherEvents: true }); }); } export interface ICalendarOverride { oid?: string; calendarId: string; description: string; status: CalendarEventStatus; startDate: Date; endDate: Date; start: string; end: string; isEntireDay: boolean; hideOtherEvents: boolean; }
506700cookie-checkReact Complex State object hook