I have yet another React useEffect question. I've read a lot of responses and I've also started from a scratch example but I still don't understand why my app makes 2 requests instead of 1.
I've initially thought it has something to do with re-rendering of components because I have a loading state and so on, but I've dumbed everything down and I still get this:
Test.tsx
import { useEffect } from "react";
const Test = () => {
//let data = { title: "Waiting for Data" };
//const [todo, setTodo] = useState(data);
//const [isData, setData] = useState(false);
//const [isFetching, setFetching] = useState(false);
useEffect(() => {
// called after the first render
async function fetchData() {
console.log(
" ----------- cause the re-render ----------- 2 ",
"setFetching = true"
);
//setFetching(true); // causing re-render - 2
const response = await fetch(
"https://jsonplaceholder.typicode.com/todos/1"
);
console.log("response = ", response);
//let data = await response.json();
console.log(" ----------- cause the re-render ----------- 3 ", "setTodo");
//setTodo(data); //updt state
console.log(
" ----------- cause the re-render ----------- 4 ",
"setFetching = false"
);
//setFetching(false);
console.log(" ----------- cause the re-render ----------- 5 ", "setData");
//setData(true);
//console.log("Data = ", data);
}
fetchData();
}, []);
return(
<>
<p>hey !</p>
</>
)
}
export default Test
index.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import Test from './components/Auth/Test';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<Test />
</React.StrictMode>
);
As you can see I've commented out everything, I've only left the console.logs and I got this result:
Here is my package.json
{
"name": "kindergarden-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.1.1",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.4.1",
"@types/node": "^16.11.29",
"@types/react": "^18.0.7",
"@types/react-dom": "^18.0.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1",
"typescript": "^4.6.3",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Do you guys have any ideas or guidance on how I can make this a single call ? Thanks !