Search code examples
reactjstypescript

react object is possible null or undefined


why I recieve this error although I make a condition check if the object exists.

Object is possible null or undefined

Code:

{
  const inHolidays = useCallback(() => data?.user.holiday_times ? checkIfEmployeeIsInHolidays(data?.user.holiday_times) : null, [data]);
....
   inHolidays() 
    ?
    <p>Mitarbeiter ist im Urlaub bis zum {format(new Date(inHolidays().end_time), 'PP', { locale: de })}</p>
    :
    <p>NOT</p>
}

the error comes here in inHolidays().end_time

{format(new Date(inHolidays().end_time)

Why I get this error ? I make a condition check inHolidays() ? : ... but not working


Solution

  • You have two things that can possibly be null/undefined here: the function itself, and the result of that function call.

    I would do the following to avoid calling the function when the function can be null, and to avoid trying to access a property on a null/undefined result.

    {
      const inHolidays = useCallback(() => data?.user.holiday_times ? checkIfEmployeeIsInHolidays(data?.user.holiday_times) : null, [data]);
      const inHolidaysResult = inHolidays && inHolidays();
    ....
       inHolidaysResult 
        ?
        <p>Mitarbeiter ist im Urlaub bis zum {format(new Date(inHolidaysResult.end_time), 'PP', { locale: de })}</p>
        :
        <p>NOT</p>
    }