Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument of type 'Date | null' is not assignable to parameter of type 'SetStateAction<Date>'

I am following the Ionic tutorial for react. I created the tutorial page and I am trying to add a datepicker element to it. This is my page right now:

import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar } from '@ionic/react';
import React, { useState } from 'react';
import DatePicker from 'react-datepicker'
import "react-datepicker/dist/react-datepicker.css";

const Home: React.FC = () => {
  const [startDate, setStartDate] = useState(new Date());
  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>Ionic Blank</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent className="ion-padding">
        The world is your oyster 14.
        <p>
          If you get lost, the{' '}
          <a target="_blank" rel="noopener noreferrer" href="https://ionicframework.com/docs/">
            docs
          </a>{' '}
          will be your guide.
        </p>
        <DatePicker selected={startDate} onChange={date => setStartDate(date)} />
      </IonContent>
    </IonPage>
  );
};

export default Home;

The datepicker that I am using is from here and I used the first example in my page:

() => {
  const [startDate, setStartDate] = useState(new Date());
  return (
    <DatePicker selected={startDate} onChange={date => setStartDate(date)} />
  );
};

However, I am getting the following error:

[react-scripts] Argument of type 'Date | null' is not assignable to parameter of type 'SetStateAction<Date>'.
[react-scripts]   Type 'null' is not assignable to type 'SetStateAction<Date>'.  TS2345
[react-scripts]     22 |           will be your guide.
[react-scripts]     23 |         </p>
[react-scripts]   > 24 |         <DatePicker selected={startDate} onChange={date => setStartDate(date)} />
[react-scripts]        |                                                                         ^
[react-scripts]     25 |       </IonContent>
[react-scripts]     26 |     </IonPage>
[react-scripts]     27 |   );

What is the problem?

like image 461
Tasos Avatar asked Dec 27 '19 07:12

Tasos


Video Answer


1 Answers

The onChange callback from react-datepicker looks like this:

onChange(date: Date | null, event: React.SyntheticEvent<any> | undefined): void;

So date potentially can be null. You have two options here:


1.) accept nullable date state in useState Hook:

const [startDate, setStartDate] = useState<Date | null>(new Date());

2.) only invoke setStartDate, when date is not null:

<DatePicker selected={startDate} onChange={date => date && setStartDate(date)} />
like image 162
ford04 Avatar answered Oct 03 '22 02:10

ford04