'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.



Solution 1:[1]

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();
  }, []);
 
}

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Carlos Querioz
Solution 2