2

I'm currently learning react and custom hooks and I got this, not sure how it's supposed to have a custom hook on this case, what should be the return, what i have to return?, any help for it will be appreciated, thank you in advance

const [newResultDate, setNewResultDate] = useState<Date>(
            (() => {
                if (value?.startDate) {
                    return new Date(value.startDate);
                } else if (value?.daysUpToDay) {
                    return new Date();
                }
                try {
                    const date = new Date(value);
                    if (date && date.toString() !== 'Invalid Date') {
                        return date;
                    }
                } catch (e) {
                    // noop
                }
                return new Date();
            })()
        );

possible custom hook:

const useCustomHook = (dateFilter: ( dateProps)) => {
    const [newResultDate, setNewResultDate] = useState<Date>();

    const setDateValue = (val) => setNewResultDate(val);

    if (dateFilter?.startDate) {
        setNewResultDate(new Date(dateFilter.startDate));
    } else if (dateFilter?.daysUpToDay) {
        setNewResultDate(new Date());
    }
    try {
        const date = new Date(dateFilter as any);
        if (date && date.toString() !== 'Invalid Date') {
            setNewResultDate(date);
        }
    } catch (e) {
        // noop
    }
    setNewResultDate(new Date());

    return [newResultDate, setDateValue] as const;
};


is this correct?

how is supposed to be used on my component?
  • Your question is unclear... what are you trying to do? Just make a custom React hook from the above snippet? Just wrap it in a function with a "use-" prefixed name and call it from a React component. – Drew Reese Jan 25 '22 at 05:48
  • @DrewReese sorry, not sure if know is more clear?, not sure what i have to return in my custom hook, Thank you – gabriel fuentes Jan 25 '22 at 06:00

1 Answers1

1

I am fairly certain you cannot call the state updater from within the lazy initialization function passed to what is effective the "constructor".

Instead of trying to "set the state", simply return the value you want the initial state to be. Pass the value to your hook so it can be passed to the initializer function.

const initializeState = (value) => {
  if (value?.startDate) {
    return new Date(value.startDate);
  } else if (value?.daysUpToDay) {
    return new Date();
  }
  try {
    const date = new Date(value);
    if (date?.toString() !== 'Invalid Date') {
      return date;
    }
  } catch (e) {
    // noop
  }
  return new Date();
});

const useCustomHook(value) => {
  const [newResultDate, setNewResultDate] = useState<Date>(() => initializeState(value));
  return [newResultDate, setNewResultDate] ;
}

Usage:

useCustomHook({ startDate: "2022-01-22" });
Drew Reese
  • 165,259
  • 14
  • 153
  • 181