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();
};
CodePudding user response:
although it's recommended to do side effects operations inside a useEffect to avoid re-renders, doing a fetch without a useEffect will cause re-renders but should not cause an infinite loop. try running this code
this is not recommended but should not cause an infinite loop
export default function App() {
const result = fetch(
"https://api.coindesk.com/v1/bpi/currentprice.json"
).then((response) => {
console.log("result", response);
});
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button onClick={()=>alert('hello')}>hello</button>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
if you set the state then you will have a an infinite loop
import "./styles.css";
import {useState} from 'react'
export default function App() {
const [data,setData] = useState([]);
const result = fetch(
"https://api.coindesk.com/v1/bpi/currentprice.json"
).then((response) => {
setData([])
console.log("result", response);
});
console.log("result", result);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button onClick={() => alert("hello")}>hello</button>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
also, see this stack overflow thread, it has more insights around this subject How to fetch data without useEffect hooks in React function component?
CodePudding user response:
I recreated your code using only the parts relevant to the fetch and I'm not seeing a re-render, or at least not an infinite loop.
For tracking down why something rerendered, check the answer here regarding the React Devtools profiler tool.
I also stumbled across a 3rd party library called 'Why Did You Render' that will console log the reason for re-renders.