Search code examples
javascriptreactjsreact-reduxredux-toolkitredux-thunk

calling dispatch function in other component


I have a multipale dispatch functions that dipatch some AsyncThunk functions i tryed to refactor the code so i want to put the multipale dispatch functions inside a function and then call it from my component for just formating the code to be readable and here is an example of my code

export default function resetAllDb() {
  const dispatch = useDispatch();

  dispatch(function1());
  dispatch(function2());
  dispatch(function3());

}

export default myComponent = () => {

const handeFormSubmit = ()=>{

//calling the dispatch function

resetAllDb()

}

return (

//Some JSX Code 

<div> 

  <form>

   <Button  onClick ={handeFormSubmit}/>

  </form>

</div>

)};

i get this error :

caught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

Solution

  • One solution would be to pass the dispatch function as an argument to resetAllDb instead of using useDispatch. You can then call resetAllDb from your component and pass it the dispatch function

    export default function resetAllDb(dispatch) {
      dispatch(function1());
      dispatch(function2());
      dispatch(function3());
    }
    
    export default myComponent = () => {
      const dispatch = useDispatch();
    
      const handeFormSubmit = ()=>{
        //calling the dispatch function
        resetAllDb(dispatch);
      }
    
      return (
        //Some JSX Code 
        <div> 
          <form>
            <Button onClick ={handeFormSubmit}/>
          </form>
        </div>
      );
    };