Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is promise response getting call twice in functional component?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading