Using react API to print a question on screen not working

I’m new to using react and I’m trying to make an application that shows the user a question from this api: https://opentdb.com/api.php?amount=1 and after the user clicks the button it should show a new question. I keep getting invalid hook call and after trying to find the answer I just can’t seem to find out why. Heres my code:

  
  

    function FetchQuestion(){
    const [triviaq, setTriviaq] = React.useState([]);


    React.useEffect(() => {
      //fetch
      fetch('https://opentdb.com/api.php?amount=1')
      .then(response => response.json())
      .then(data => {
        setTriviaq(data.results[0].question);
      })
      .catch(err => console.error(err))
    }, []);

    

    return(
    
    <div>
      Question: {triviaq}
     <button onClick={FetchQuestion}> Next Question </button>
      
      </div>
    )

    }
    
    
  
  ReactDOM.render(<FetchQuestion/>, document.getElementById("root"))
  
  </script>```

Answer

That’s because you are trying to call your own react component instead of calling a function which you should define inside your component to trigger during onClick event. Additionally, here you’re using useEffect without any dependency on it, in order to call it only during the initial rendering. Create a separate function to be called during initial rendering and onClick event as follows.

export default function FetchQuestion() {
  const [triviaq, setTriviaq] = React.useState([]);

  const fetchNextQuestion = () => {
    //fetch
    fetch("https://opentdb.com/api.php?amount=1")
      .then((response) => response.json())
      .then((data) => {
        setTriviaq(data.results[0].question);
      })
      .catch((err) => console.error(err));
  };

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

  return (
    <div>
      Question: {triviaq}
      <button onClick={fetchNextQuestion}> Next Question </button>
    </div>
  );
}

Hope this would solve your issue.