I am making a simple get request in React like the following:
function App() {
const [req, setReq] = useState();
const getBasic = () => {
axios
.get(
"https://financialmodelingprep.com/api/v4/price-target?symbol=AAPL&apikey=********"
)
.then((result) => setReq(result));
};
useEffect(() => {
getBasic();
}, []);
console.log(req);
return (
<div>
</div>
);
}
The above code logs the same thing four times in the console.
Was not sure if moving the console.log(req)
into the return would do anything different, like:
return (
<div>
{console.log(req)}
</div>
);
It did not however and had the same result.
I tried to do the same code but with async await syntax:
function App() {
const [req, setReq] = useState();
const getBasic = async () => {
const getReq = await axios.get(
"https://financialmodelingprep.com/api/v4/price-target?symbol=AAPL&apikey=**********"
);
setReq(getReq);
};
useEffect(() => {
getBasic();
}, []);
console.log(req);
return (
<div>
</div>
);
}
Still the same, getting four seperate console.log(req)
's in console.
The last thing I tried was using a onClick button instead of useEffect to make a request
return(
<div>
<button onClick={getBasic} />
</div>
)
this results into two logs per click instead of four with useEffect
.
I do not understand if in these instances I am making two or four requests or if I am still only making one request but it is logging multiple times, I would like to know why this is happening and what I should do to fix it, even though I can do the rest of my project with it working this way it appears I am not doing it optimally either way.