I have several components that are scheduled repeatedly in them. I want to use a helper function to import and use in multiple components. Maddeningly, it’s not easy—at least for me. Read a lot about this but can't relate to it.
The problem I encountered was react-dom.development.js:16227 Uncaught Error: Invalid hook call. Hooks can only be called inside the body of a functional component. This may occur for one of the following reasons: You may be violating Hooks rules
So how to call scheduling in the auxiliary function? I think custom hooks might be the way to go - will have a look at it now.
Example of streamlined components:
...imports... import { helperCall } from '../../assets/helperFunctions/helperCall'; export default function CompExamp() { ...variables... return ( <div className="min-w-0 flex-1" onClick={(e) => helperCall(e, searchText, searchType)} > <span className="absolute inset-0" aria-hidden="true" /> <p className="text-sm font-medium text-black">Target</p> <p className="text-base text-gray-700">test</p> </div> ) }
Simplified auxiliary functions:
import React from 'react'; import { useDispatch } from 'react-redux'; import { useNavigate } from 'react-router-dom'; import { loadASearchResults, updateASearchTerm } from '../../redux/actionsReducers/AResults'; import { loadBSearchResults, updateBSearchTerm } from '../../redux/actionsReducers/BResults'; import { loadCSearchResults, updateCSearchTerm } from '../../redux/actionsReducers/CResults'; export function helperCall(e: any, searchText: string, searchType: string) { const dispatch = useDispatch(); const navigate = useNavigate(); e.preventDefault(); e.stopPropagation(); if (!searchText || searchText === '-' || searchText.toLowerCase() === 'not listed') { return; } if (searchType === 'a') { dispatch(updateASearchTerm({ searchTerm, searchType })); dispatch(loadASearchResults({ searchTerm, searchType })); navigate('/page-a'); } else if (searchType === 'b') { dispatch(updateBSearchTerm({ searchTerm, searchType })); dispatch(loadBSearchResults({ searchTerm, searchType })); navigate('/page-b'); } else if (searchType === 'c') { dispatch(updateCSearchTerm({ searchTerm, searchType })); dispatch(loadCSearchResults({ searchTerm, searchType })); navigate('/page-c'); } }
You can only use React hooks in React functional components, but you can pass functions to helper functions like this: