Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function every minute in a React component?

I make a table to get stock price quotes, it works well, but when I try to put a function include setState in the component, it falls into an infinite loop, it triggers setState and re-render immediately and triggers again.

How can I call this function without triggering an infinite loop when I load this component? I would to call the function every 10 seconds or every minute.

import React, { useState } from 'react'
import api from '../../api'

function CreateRow(props){
    
    const [stock, setStock] = useState({symbol:'',last:'',change:''})
    

    async function check() {
        const result = await api.getStock(props.item)
        console.log(props.item)
        const symbol = result.data.symbol
        const lastest = result.data.latestPrice
        const change = result.data.change
        setStock({symbol:symbol, lastest:lastest, change:change})
    }


    // check()   <----------! if I call the function here, it becomes an infinite loop.


    return(
        <tr>
            <th scope="row"></th>
            <td>{stock.symbol}</td>
            <td>{stock.lastest}</td>
            <td>{stock.change}</td>
        </tr>
    )
}

export default CreateRow
like image 518
Jeff Guo Avatar asked Nov 28 '20 12:11

Jeff Guo


People also ask

How do you call a function automatically in React?

In React, the onClick handler allows you to call a function and perform an action when an element is clicked. onClick is the cornerstone of any React app. Click on any of the examples below to see code snippets and common uses: Call a Function After Clicking a Button.

How do you run a function every second in React?

Let's explore how to use setInterval in React. The TL;DR: useEffect(() => { const interval = setInterval(() => { console. log('This will run every second!'

How do you call a function after 2 seconds React?

The setTimeout method allows us to run a function once after the interval of the time. Here we have defined a function to log something in the browser console after 2 seconds. const timerId = setTimeout(() => { console. log('Will be called after 2 seconds'); }, 2000);

How do you set intervals in React?

Run setInterval() from a React button onClick event To stop the interval with a button click, you need to save the interval ID returned by the setInterval() method as a state value. Next, modify the handleClick() function and add an if block that checks for the intervalId value first.


Video Answer


2 Answers

You want to initiate a timeout function inside a lifecycle method.

Lifecycle methods are methods which call on, for example, mount and unmount (there are more examples but for the sake of explanation I will stop here)

what you're interested in is the mount lifecycle.

In functional components, it can be accessed like this:

const { useEffect } from 'react';

useEffect(() => {
  // This will fire only on mount.
}, [])

In that function, you want to initialize a setTimeout function.

const MINUTE_MS = 60000;

useEffect(() => {
  const interval = setInterval(() => {
    console.log('Logs every minute');
  }, MINUTE_MS);

  return () => clearInterval(interval); // This represents the unmount function, in which you need to clear your interval to prevent memory leaks.
}, [])
like image 170
Antonio Erdeljac Avatar answered Oct 24 '22 13:10

Antonio Erdeljac


Consider 60000 milliseconds = 1 minute

Can do using the method:

setInterval(FunctionName, 60000)

do as below:

async function check() {
  const result = await api.getStock(props.item)
  console.log(props.item)
  const symbol = result.data.symbol
  const lastest = result.data.latestPrice
  const change = result.data.change
  setStock({symbol:symbol, lastest:lastest, change:change})
}

// Write this line

useEffect(() => {
  check()
 }, []);


setInterval(check, 60000);
like image 28
aish Avatar answered Oct 24 '22 14:10

aish