I am fairly new to React. I am currently having the problem that I am using the Axios Get request response to update one of my state variables.
However, I am currently facing the problem in which because the state variable is being updated, App gets re-rendered, which then calls the Axios Get request again (causing a sorta infinite loop).
How do I make it so that a Get request can change a variable, but doesn’t re-render the component and call a Get request again?
function App(props) {
let [sentenceData, setSentenceData] = React.useState({})
const renderEnglishSentence = useCallback(function () {
return <EnglishSentence sentenceData={sentenceData}/>;
}, [sentenceData]);
const fetchSentence = useCallback(function() {
return axios.get('http://localhost:3030/getrandomunusedsentence')
})
fetchSentence().then((response) =>
setSentenceData(response.data[0])
return (
<div>
{renderEnglishSentence()}
</div>
)
)
}
>Solution :
const [sentenceData, setSentenceData] = React.useState({})
React.useEffect(() => {
axios.get('http://localhost:3030/getrandomunusedsentence')
.then(() => {
setSentenceData(response.data[0])
})
}, [])
You can make the http request in the useEffect hook with zero dependencies ([])