Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why my "new Question" button is not changing the question when i click the button?

So the idea is when you click the button, you should see new question. But its not working and i don’t know why 🙁 Help!

  const Trivia = () => {
      const [question, setQuestion] = React.useState();
     
  
      React.useEffect(() => {

             fetch('https://opentdb.com/api.php?amount=1') 
            .then(response => response.json())
            .then(data => {
             setQuestion(data.results[0].question);

             });
      }, [] )
      

      return(
      <div>
            <p>{question}</p> 
              
            <button onClick={() => }> New Question</button>
      </div>
      
      );
  };
      
  ReactDOM.render(<Trivia />, document.getElementById("root"));
</script>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So if you want to refetch a new question from your API when you click the button, I suggest you to export your API call into a function like that :

    const fetchQuestion = () => {
    fetch("https://opentdb.com/api.php?amount=1")
      .then((response) => response.json())
      .then((data) => {
        setQuestion(data.results[0].question);
      });
  };

Then you can call it whenever you want, and your code should be like this :

const Trivia = () => {
  const [question, setQuestion] = React.useState();

  const fetchQuestion = () => {
    fetch("https://opentdb.com/api.php?amount=1")
      .then((response) => response.json())
      .then((data) => {
        setQuestion(data.results[0].question);
      });
  };

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

  return (
    <div>
      <p>{question}</p>

      <button onClick={fetchQuestion}>New Question</button>
    </div>
  );
};

ReactDOM.render(<Trivia />, document.getElementById("root"));
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading