Home > Software engineering >  Call useEffect after some interval
Call useEffect after some interval

Time:08-14

I want to call a function only once after some interval in my app for that I have choosed the hook useEffect. Not I want to call it after some interval to make a variable account defined which comes from useEthers()

Any help will be appriciated.

The script I am using :

// import { useEffect, useState } from "react"
import { useEthers, useContractFunction, useCall, useLogs} from       const i = () => {

    console.log(account) //I want to log the account after 3 secs
    toast.info('Fetching content...' )
    // console.log('Signin calling now??', account)
    // SignIn()
  }
  useEffect(() => {
    i()
  }, []) // add [] to only call this once
    return (
        <div>
        <h1 >Hello this is login activity {account}</h1>
        </div>
    )

}

CodePudding user response:

[based on a lengthy comment thread on the question...]

You're over-thinking it. And pretty much any time you want to introduce an artificial delay because of an asynchronous operation, it's the wrong approach.

What you want to do isn't this:

Wait for a few seconds and print the account value

What you want to do is this:

Print the account value when it's available

The simplest solution then would be to print it wherever it comes from. For example, if it's fetched from an asynchronous operation, then the console.log would go in the response to that operation.

But as for useEffect, the way you'd accomplish this is by using account as a dependency of the effect:

useEffect(() => {
  // this code will run any time "account" changes
}, [account]);

So to log it to the console:

useEffect(() => {
  console.log(account);
}, [account]);

Or only log it if it's non-null (or "truthy"):

useEffect(() => {
  if (account) {
    console.log(account);
  }
}, [account]);

Whatever the operation is, useEffect will re-trigger it any time something in the dependency array changes. (When the dependency array is empty, the effect is only triggered on the first render. When the dependency array is omitted, the effect is triggered on every render.)

  • Related