How to call the usehook within a function using react?

Viewed 290

I want to return a function that uses useEffect from the usehook and i am getting this error...

useEffect is called in a function which is neither a react function component or custom hook.

What am I trying to do?

I have addbutton component and when user clicks add button i want to call the function requestDialog.

Below is my code within addbutton file

function AddButton () {
   const count = useGetCount();
   const requestDialog = useRequestDialog(); // using usehook here
   on_add_click = ()  => {
      requestDialog(count); // calling requestDialog here
   }

   return (
      <button onclick={on_add_click}>add</button>
   );
}


interface ContextProps {
   trigger: (count: number) => void;
}

const popupContext = React.createContext<ContextProps>({
   trigger: (availableSiteShares: number) => {},
});

const usePopupContext = () => React.useContext(popupContext);

export const popupContextProvider = ({ children }: any) => {
   const [show, setShow] = React.useState(false);
   const limit = 0;

   const dismiss = () => {
      if (show) {
         sessionStorage.setItem(somePopupId, 'dismissed');
         setShow(false);
      }
   };

   const isDismissed = (dialogId: string) =>
      sessionStorage.getItem(dialogId) === 'dismissed';

      const context = {
          trigger: (count: number) => {
             if (!isDismissed(somePopupId) && count <= limit) {
                setShow(true);
             } else if (count > limit) {
                setShow(false);
             }
          },
      };

      return (
          <popupContext.Provider value={context}>
             {children}
             {show && (
                 <Popup onHide={dismiss} />
             )}
          </popupContext.Provider>
      );
};

 
export function useRequestDialog(
   enabled: boolean,
   count: number
) {
   return function requestDialog() { //here is the error
      const { trigger } = usePopupContext();
      React.useEffect(() => {
         trigger(count);
      }
   }, [count, trigger]);
}

How can I modify this code in useRequestDialog such that i can call the useEffect here.

Could someone help me with this? thanks.

1 Answers

The useEffect hook needs to be outside of the return as it lets you perform other actions outside of the return for functional components. The example in the React docs shows a good example of it: useEffects

So for your example it would look something like:

const useRequestDialog = ({...}) => {

 React.useEffect(() => {
    trigger(count);
 }, [count, trigger]);

 return {...}

But if you want to just call the requestDialog function, you might be able to do something like:

const requestDialog = (count) => {
   const x = something(count);
   return x;
}

const AddButton = () => {
   const count = useGetCount();
   const handleClick = ()  => {
      requestDialog(count);
   }

   return (
      <button onClick={handleClick}>add</button>
   );
}
Related