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?
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" });