I'm making a table to get stock price quotes, it works well, but when I try to put a function including setState
in the component, it falls into an infinite loop, it triggers setState
and re-renders immediately and triggers again.
How can I call this function without triggering an infinite loop when I load this component? I would like 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
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:
import { 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.
}, [])