Home > Enterprise >  Date is possibly null
Date is possibly null

Time:04-03

i made a function that will take the date and then change it to a string, however typescript says that it is possibly null, how would i make typescript happy.

i am using MUI date picker and recoil, i want to push the date to a global state to use for later

 // Start Date

  const [startDate, setStartDate] = useRecoilState(StartDateState);

  const [value, setValue] = React.useState<Date | null>(
    new Date("2014-08-18T21:11:54")
  );

  const handleChange = (newValue: Date | null) => {
    setValue(newValue);
    setStartDate(newValue.toString());
  };

error above = (parameter) newValue: Date | null Object is possibly 'null'.ts(2531)

My Atom is

export const StartDateState = atom({
  key: "StartDateState",
  default: "",
});

My ui that i want to show it in is

 const date = useRecoilValue(StartDateState);

  Start Date : {date ? date : "No Start Date"}

So in total i want to push the date to a global state and use it somewhere else.

CodePudding user response:

you should not use Date | null

it should be Date only

because you can not show the null inside of JSX

CodePudding user response:

The answer i found that worked is this

 const handleChange = (newValue: Date | null) => {
    setValue(newValue);
    setStartDate(newValue ? newValue.toString() : "");
  };

and my atom to be

import { atom } from "recoil";


export const StartDateState = atom({
  key: "StartDateState",
  default: "",
});


  • Related