I am fairly new to React and trying to fetch data from mySQL caused an infinite loop. I have read many other posts and found out that the best practice if to use a useEffect Hook when fetch data. I could see the reason being that in other posts others use useState as well to get the data and change the state hence cause the infinite loop. But why does simply fetch data without changing any state would still cause infinite loop? Is that because fetch would automatically cause component rerender?
const Players = () => {
const [players, setPlayers] = useState();
const selectedPlayerName = window.location.search
? window.location.search.substring(1).split("=")[1]
: "DeMar DeRozan";
getPlayer(selectedPlayerName).then((res) => {
console.log(res.results[0]);
});
return (
<>
<MenuBar />
<div style={{ width: "70vw", margin: "0 auto", marginTop: "2vh" }}>
<img
// src={process.env.PUBLIC_URL + "/photos/legend.jpg"}
src="/photos/legend.jpg"
alt="pc"
/>
<Table
dataSource={players}
columns={playerColumns}
pagination={{
pageSizeOptions: [10],
defaultPageSize: 10,
showQuickJumper: true,
}}
/>
</div>
<Divider />
</>
this is my code for getPlayer which is simply a fetch.
const getPlayer = async (name) => {
var res = await fetch(
`http://${config.server_host}:${config.server_port}/player?name=${name}`
);
return res.json();
};