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>
)
)
}
You will want to use the useEffect hook for this. This will only render first time component is loaded.
import React, { useState, useEffect } from 'react';
function App(props) {
useEffect(() => {
const fetchSentence = useCallback(function() {
return axios.get('http://localhost:3030/getrandomunusedsentence')
})
}, []);
}
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 ([])
Api calls should be handled as side effect. You should use useEffect hook for it with no deps, so it will be called once component is mounted.
useEffect(() => {
const fetch = async () => {
const response = await axios.get('http://localhost:3030/getrandomunusedsentence');
const data = await response.json();
setSentenceData(data);
}
fetch();
}, []);