#113325
Markov
Keymaster

Hi,

Below is a React example with state management.

import React, { useEffect, useMemo, useReducer } from "react";
import { DateTimePicker } from "smart-webcomponents-react/datetimepicker";

type PickerState = {
  value: Date | null;
  timezone: string; // IANA name if you want to store it alongside
  dirty: boolean;
};

type Action =
  | { type: "setValue"; value: Date | null }
  | { type: "setTimezone"; timezone: string }
  | { type: "load"; state: PickerState }
  | { type: "resetNow" }
  | { type: "markSaved" };

const STORAGE_KEY = "demo.smart.datetimepicker.state";

function reducer(state: PickerState, action: Action): PickerState {
  switch (action.type) {
    case "setValue":
      return { ...state, value: action.value, dirty: true };
    case "setTimezone":
      return { ...state, timezone: action.timezone, dirty: true };
    case "resetNow":
      return { ...state, value: new Date(), dirty: true };
    case "markSaved":
      return { ...state, dirty: false };
    case "load":
      return action.state;
    default:
      return state;
  }
}

function safeParseStoredState(raw: string | null): PickerState | null {
  if (!raw) return null;
  try {
    const obj = JSON.parse(raw);
    return {
      value: obj.value ? new Date(obj.value) : null,
      timezone: typeof obj.timezone === "string" ? obj.timezone : "UTC",
      dirty: false,
    };
  } catch {
    return null;
  }
}

export default function DateTimePickerStateDemo() {
  const initial = useMemo<PickerState>(() => {
    const stored = safeParseStoredState(localStorage.getItem(STORAGE_KEY));
    return (
      stored ?? {
        value: new Date(),
        timezone: "UTC",
        dirty: false,
      }
    );
  }, []);

  const [state, dispatch] = useReducer(reducer, initial);

  // Persist whenever value/timezone changes
  useEffect(() => {
    localStorage.setItem(
      STORAGE_KEY,
      JSON.stringify({
        value: state.value ? state.value.toISOString() : null,
        timezone: state.timezone,
      })
    );
  }, [state.value, state.timezone]);

  // Smart Web Components typically emit CustomEvent with <code>detail.value</code>
  const handleChange = (e: any) => {
    const next = e?.detail?.value ?? null;
    // <code>next</code> is usually a Date; if it comes as string, normalize:
    const nextDate = next instanceof Date ? next : next ? new Date(next) : null;
    dispatch({ type: "setValue", value: nextDate });
  };

  const save = () => dispatch({ type: "markSaved" });

  return (
    <div style={{ padding: 16, display: "grid", gap: 12, maxWidth: 520 }}>
      <h3 style={{ margin: 0 }}>Smart.DateTimePicker + reducer state</h3>

      <DateTimePicker
        value={state.value ?? undefined}
        calendarButton
        spinButtons
        // Optional: set format-related props you like
        // formatString="dd-MMM-yyyy HH:mm"
        onChange={handleChange}
      />

      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
        <button onClick={() => dispatch({ type: "resetNow" })}>Now</button>
        <button
          onClick={() =>
            dispatch({
              type: "setValue",
              value: state.value ? new Date(state.value.getTime() + 60_000) : new Date(),
            })
          }
        >
          +1 min
        </button>
        <button
          onClick={() => {
            localStorage.removeItem(STORAGE_KEY);
            dispatch({
              type: "load",
              state: { value: new Date(), timezone: "UTC", dirty: false },
            });
          }}
        >
          Clear storage
        </button>

        <button disabled={!state.dirty} onClick={save}>
          {state.dirty ? "Save (mark clean)" : "Saved"}
        </button>
      </div>

      <div style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", fontSize: 12 }}>
        <div>value (ISO): {state.value ? state.value.toISOString() : "null"}</div>
        <div>timezone: {state.timezone}</div>
        <div>dirty: {String(state.dirty)}</div>
      </div>
    </div>
  );
}

Best regards,
Markov

Smart UI Team
https://www.htmlelements.com/