Home > front end >  Im getting invalid hook call error with useCallBack in React
Im getting invalid hook call error with useCallBack in React

Time:07-27

im getting invalid hook call error in my project.

 <DateBottomSheet
          key={keyIndexStartDate}
          currentDate={startDate}
          headerTitle={moment(startDate).format('MMMM YYYY')}
          backdropComponent={renderBackdrop}
          ref={sheetRefStartDate}
          snapPoints={snapPointsDateSheet}
          markedDates={markedStartDate}
          onChange={() => handleSheetChanges}
          renderArrow={renderCalendarRightAndLeftIcon}
          onPressArrowRight={()=>onPressCalendarRight(startDate, 'startDate')}
          onPressArrowLeft={()=>onPressCalendarLeft(startDate, 'startDate')}
          onDayPress={day => {
            setMarkedStartDateValue(day.dateString);
            pressOpenStartTimerAction();
            // handleSnapPress(1, CreateWorkyBS.startTime);
          }}
          onPressCancel={() =>
            handleCloseStartCalender(CreateWorkyBS.startDate)
          }
          onPressSave={() => saveStartDateItem()}
          saveButtonDisable={buttonStartDateDisable}></DateBottomSheet>

and is my OnpressCalendar function

const onPressCalendarRight = (date, type) => 
useCallback(add => {
  const addDate = moment(date).add(1, 'M');
  type == 'startDate' ? setStartDate(addDate) : setEndDate(addDate);
  add();
});

Error Screenshoot

Anyone help me ?

CodePudding user response:

You are breaking the Rules of Hooks. useCallback is a hook, and as such can ONLY be called at the root level of a functional component.

It looks like you can simply remove the use of useCallback altogether to fix the issue, and call the embedded function directly in onPressCalendarRight.

const onPressCalendarRight = (date, type) => {
  const addDate = moment(date).add(1, 'M');
  type == 'startDate' ? setStartDate(addDate) : setEndDate(addDate);
}

CodePudding user response:

Try this

 onPressCalendarRight = useCallback((add) => (date,type) => {
 const addDate = moment(date).add(1, 'M');
  type == 'startDate' ? setStartDate(addDate) : setEndDate(addDate);
  add();
 },[]);
  • Related