Skip to content
Advertisement

React Hook “useState” is called in function

I have button click system and it works.

function clickCreate(msg){
    console.log(msg);
}
const CreateButton = (props) =>{
  return(
    <div>
    <i onClick = {() => clickCreate("test")} id="createBtn" className="fas fa-5x fa-microphone-alt"></i>
    </div>
  );
}

Now I want to fetch the API inside the function.

So, change the function clickCreate like this

function clickCreate(msg){
  const [result, setResult] = useState([]);
  useEffect(() => {
    axios.get('http://localhost:8000/api/genres/')
      .then((res)=> {
      console.log(res.data.items);
      setResult(res.data.items);
    }).catch(err=>{console.log(err);});
  }, []);
}

However there comes error like this.

I should not use useState and useEffect in function, but how can trigger the API by btn click??

./src/views/Components/Components.js
  Line 168:31:  React Hook "useState" is called in function "clickCreate" which is neither a React function component or a custom React Hook function   react-hooks/rules-of-hooks
  Line 170:3:   React Hook "useEffect" is called in function "clickCreate" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

Search for the keywords to learn more about each error.

Advertisement

Answer

You should move the hook to component level (Rules of hooks), then you can fetch on click and use the hook’s setter:

const CreateButton = (props) => {
  const [result, setResult] = useState([]);

  // should be in scope with `setResult`
  function clickCreate() {
    axios
      .get("http://localhost:8000/api/genres/")
      .then((res) => {
        console.log(res.data.items);
        setResult(res.data.items);
      })
      .catch((err) => {
        console.log(err);
      });
  }

  return (
    <div>
      <i
        onClick={clickCreate}
        id="createBtn"
        className="fas fa-5x fa-microphone-alt"
      ></i>
    </div>
  );
};
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement