reactjstypescriptdevextremedevextreme-react

How to solve TypeError of getFullYear() function with devextreme Datebox?


Recently, I encountered an issue which the devextreme-react date-box cannot change its value with onValueChanged function, and it returns the below error:

Uncaught TypeError: t.getFullYear is not a function
    at w (dx.all.js:19:2246625)
    at x (dx.all.js:19:2246540)
    at Object.sameDate (dx.all.js:19:2249338)
    at t._valueChangedHandler (dx.all.js:19:1580825)
    at Object.execute (dx.all.js:19:2166269)
    at l._executeAction (dx.all.js:19:2165470)
    at l.execute (dx.all.js:19:2165081)
    at t.<anonymous> (dx.all.js:19:2173158)
    at t.l [as _valueChangeAction] (dx.all.js:19:2173871)
    at t._raiseValueChangeAction (dx.all.js:31:453687)

This is the sample code that I tested with it:

function App() {
  const [dateValue, setDateValue] = useState<string>("");

  const onDateValueChanged = (e: ValueChangedEvent) => {
    setDateValue(e.value);
  }

  return (
    <div>
      <DateBox
        type="datetime"
        dateSerializationFormat="yyyy-MM-dd HH:mm:ss"
        displayFormat="yyyy-MM-dd HH:mm:ss"
        isRequired={true}
        isDisabled={false}
        isReadonly={false}
        value={dateValue}
        onValueChanged={onDateValueChanged}
        max={new Date()}
      />
    </div>
  );
}

Solution

  • I've tried checking the documentation. Instead of treating the dates as string can you do do it as Date object itself and see if it works?


    Why this happens?

    I'm assuming the DateBox library is calling the getFullYear on Date internally. While Date object has this method, strings don't - hence your code is crashing.

    Give me a fix

    1. At first, change the state to use Date object instead of string.
    const [dateValue, setDateValue] = useState(new Date(1981, 3, 27));
    

    Note (from your comments): It seems like setting null as default value also works. This is probably because null quite represents empty value - and they might be using placeholders to cover it up.

    So simply, you can do this:

    const [dateValue, setDateValue] = useState(null);
    
    1. Update the onDateValueChanged callback:
      const onDateValueChanged = useCallback((e: DateBoxTypes.ValueChangedEvent) => {
        setDateValue(e.value);
      }, []);
    

    Hope this helps.