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

59
Vistas
Trying to console.log data within useEffect. Not logging any information
function UserAccounts() {
  const [accounts, setAccounts] = useState();

  useEffect(() => {
    async function fetchAccounts() {
      const res = await fetch(
        'https://proton.api.atomicassets.io/atomicassets/v1/accounts'
      );
      const { accounts } = await res.json();

      setAccounts(accounts);
      console.log(accounts);
    }

    fetchAccounts();
  }, []);
 
}

I'm trying to understand why console.log shows nothing in this example and what is the correct way to console.log the data that is being fetched from the api.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Well, you need to get the structure of the returned payload from the API correct. It does not have an accounts property.

The payload looks like this:

{
  "success":true,
  "data":[{"account":"joejerde","assets":"11933"},{"account":"protonpunks","assets":"9072"}],
  "queryTime": 1646267075822
}

So you can rename the data property while destructuring. const { data: accountList } = await res.json();

function UserAccounts() {
  const [accounts, setAccounts] = useState();

  useEffect(() => {
    async function fetchAccounts() {
      const res = await fetch(
        'https://proton.api.atomicassets.io/atomicassets/v1/accounts'
      );
      const { data: accountList } = await res.json();

      setAccounts(accountList);

      // logging both the state and the fetched value
      console.log(accounts, accountList);
      // accounts (state) will be undefined
      // if the fetch was successful, accountList will be an array of accounts (as per the API payload)
    }

    fetchAccounts()
  
  }, [])

  return <div>
    {JSON.stringify(accounts)}
  </div>
}

Edit: using some other variable name while destructuring, confusing to use the same variable name as the state (accounts).

Working codesandbox

about 4 years ago · Juan Pablo Isaza Denunciar

0

One thing I would change is working with try/catch surrounding async/await statements. If your await statement fails it will never reach the console.log statement. Unless you have another component handling those errors, I would use it in that way.

That is my suggestion:

function UserAccounts() {
  const [accounts, setAccounts] = useState();

  useEffect(() => {
    try {
     async function fetchAccounts() {
      const res = await fetch(
        'https://proton.api.atomicassets.io/atomicassets/v1/accounts'
      );
      const { accounts } = await res.json();

      setAccounts(accounts);
      console.log(accounts);
     }
    } catch (err) {
      console.log(err)
      // do something like throw your error
    }

    fetchAccounts();
  }, []);
 
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

since state function runs asyncronousely . therefore when you use setAccounts it sets accounts variable in async way , so there is a preferred way of doing this thing is as below

problems i seen

1.fetch result should destructured with data instead of accounts variable

2.setAccounts function is running async way so it will not print result immedietly in next line

import { useEffect, useState } from "react";

export default function App() {
  const [accounts, setAccounts] = useState();

  async function fetchAccounts() {
    const res = await fetch(
      "https://proton.api.atomicassets.io/atomicassets/v1/accounts"
    );
    const { data } = await res.json();
    setAccounts(data);
  }

  // on component mount / onload
  useState(() => {
    fetchAccounts();
  }, []);

  // on accounts state change
  useEffect(() => {
    console.log(accounts);
  }, [accounts]);

  return <div className="blankElement">hello world</div>;
}

check here sample

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