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 :
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>