Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
Infinite console log in react js component

I have made two simple straight forward component is React, used a open source API to test API integration. React is showing this weird behavior of infinite console logs. I don't understand the issue. I'm using the fetch function for making API calls and functional component.

App component:

function App() {

 const [characters, setCharac] = useState([])

  const URL = "https://swapi.dev/api/";

   fetch(URL + "people").then(response => response.json().then(data => {
     setCharac(data.results)
     console.log('Test');
   }))

  return (
    <div className="App">
      {characters.map(charac => {
        return <Character {...charac} />
      })}
    </div>
  );
}

Character component:

const Character = (props) => {
  console.log(props);
  return (
    <div key={props.name}>
      <h1>{props.name}</h1>
      <p>{props.height}</p>
    </div>
  );

}

console.log('Test'); in App component and console.log(props); in Character component are being executed infinitely.

This is the render method

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Try wrapping it in a useEffect

e.g.

useEffect(()=>{
fetch(URL + "people").then(response => response.json().then(data => {
     setCharac(data.results)
     console.log('Test');
   }))
},[])

otherwise every time the state is set it is firing off the fetch again because a re-render is being triggered.

about 4 years ago · Juan Pablo Isaza Relatório

0

Your components are rendering multiple times because your state is changed every time you fetch data (because of setState).

Try creating a function fetchData(). Make this function async as well to wait for data to be retrieved.

const fetchData = async () => {
   const result = await fetch(URL + "people").then(response => response.json().then(data => {
    setCharac(data.results)
    console.log('Test');
    return data;
   }));
   return result;
}

and then use it inside useEffect (Read more about useEffects: React hooks: What/Why `useEffect`?)

useEffect(() => {
   fetchData();
}, []);

Note the usage of [] in useEffect. The data will be fetched only once when you load the component.

about 4 years ago · Juan Pablo Isaza Relatório

0

Because you fetch some data, update the state, which causes a re-render, which does another fetch, updates the state, which causes another render...etc.

Call your fetch function from inside a useEffect with an empty dependency array so that it only gets called once when the component is initially rendered.

Note 1: you can't immediately log the state after setting it as setting the state is an async process. You can, however, use another useEffect to watch for changes in the state, and log its updated value.

Note 2: I've used async/await in this example as the syntax is a little cleaner.

// Fetch the data and set the state
async function getData(endpoint) {
  const json = await fetch(`${endpoint}/people`);
  const data = await response.json();
  setCharac(data.results);
}

// Call `getData` when the component initially renders
useEffect(() => {
  const endpoint = 'https://swapi.dev/api';
  getData(endpoint);
}, []);

// Watch for a change in the character state, and log it
useEffect(() => console.log(characters), [characters]);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda