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

125
Visualizações
I'm fetching a problem when I'm trying to fetch data from an API by using useEffect in react
const [users, setUsers] = useState([]);
const getUsers = async () => {
    const URL = "https://jsonplaceholder.typicode.com/users";
    const response = await fetch(URL);
    const data = await response.json();
    console.log(data); // return 10 array . 
    setUsers(data);
    console.log(users); // return empty Array 
};
useEffect(() => {
    getUsers();
}, []);

when I run this code and reload the browser, the data variable shows 10 arrays (that's what I expected) and the users state doesn't return an empty array (that's the problem). And then I'm changing something on code, and come to the browser, data variable and users state both shows 10 arrays. That means I'm trying to tell you that, when I'm reloading the browser for the first time state doesn't set from data variable . See the console result to better understand

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Setting a state is an asynchronous process. That's why you won't see the immediate effect after calling the setUsers(). Rather you can add another useEffect in your code and see the changes happening for users

// ... other code
useEffect(() => {
    // this will run after the 'users' has been changed
    console.log("Users", users)
}, [users]);
// ...

After adding this useEffect you will see that the users will be printed after it is updated.

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