Home > Net >  How to make "dispatch" as export function in React JS?
How to make "dispatch" as export function in React JS?

Time:01-29

This is my dispatch function:

DispatchRecipeID.js

    import { useDispatch } from "react-redux";
    import { UpdateRecipeID } from "../store/action/recipeId";
    
    const DispatchRecipeID = (id) => { 

      const dispatch = useDispatch(); // dispatch
    
      dispatch(UpdateRecipeID(id));
    
    };
    
    export default DispatchRecipeID;
    

Now I am use this DispatchRecipeID() function in another React JS file.

Navbar.js

        import React, { useState } from "react";
        import DispatchRecipeID from "../../middleware/DispatchRecipeID";

    
    const Navbar = () => {

            // inputbox value
            const [input, setInput] = useState("");
            // get search item info from inputID. using inputID.id
            const [inputID, setInputID] = useState(null);

            // search function
            const dispatchRecipeID = ()=>{
              if(input !== "" && input !== null ){
               DispatchRecipeID(inputID.id)
              }
              return
            }
          
            // ....... some code
            return(
                <div>
                  <input type="text" value={input}   onChange={(event,value)=>{ setInputID(value) }} /> 
                  <button onClick={dispatchRecipeID(input)} >Search</button> 
                </div>
            )
            
  }

  export default Navbar;

But I get error:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

Full Error Here:

react-dom.development.js:14906 Uncaught 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 See enter image description here


    How to fix this error? And I want use DispatchRecipeID() function at "3 or 4 JS" files like as Navbar.js

    please help me, and thanks :)

    CodePudding user response:

    just for reminding the one of the important rules in the react hooks that you can't use hooks inside the nested functions and they will not work if you brake this rule

    check your all component

  •  Tags:  
  • Related