I have this code that uses a promises, but my issue is when I console.log the response it prints it 2 times, why is that? Can anyone point me in the right direction? thanks in advance!
import "./App.css";
import { useState } from "react";
function App() {
const [data, setData] = useState([]);
let itemsApi = new Promise(function (resolve, reject) {
setTimeout(() => {
resolve([
{ grupoId: 1, name: "test1" },
{ grupoId: 2, name: "test2" },
{ grupoId: 1, name: "test3" }
]);
}, 500);
});
itemsApi
.then((res) => {
console.log(res); // This gets call 2 times, why??
})
.catch((error) => {});
return <div>test</div>;
}
export default App;
>Solution :
React is free to call your component function as many times as it feels like (and indeed, in Strict Mode it usually calls it twice, to make sure you’re not doing bad things with side effects — as you now are).
Here’s an example of how to properly do async data loading using useEffect.
loadData here is just a mock function that takes 500 milliseconds to return data, but could be anything else too.
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function loadItems() {
const data = [
{ grupoId: 1, name: "test1" },
{ grupoId: 2, name: "test2" },
{ grupoId: 1, name: "test3" },
{ grupoId: 1, name: "test4" },
{ grupoId: 3, name: "test5" },
{ grupoId: 2, name: "test6" },
];
await delay(500);
return data;
}
function App() {
const [data, setData] = useState([]);
React.useEffect(() => {
loadItems().then(setData);
}, []); // <- empty dependency array has this effect only run once
return <div>{JSON.stringify(data)}</div>;
}
export default App;