Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda