Please, how do I use interval inside componentDidMount in react native?
I want to call receiveData in interval when componentMounts
time:date.now is there just from example, I dont know how to replace it with my function for it to work
componentDidMount() {
this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
receiveData = () => {
this.socket.on('data', (data) =>{
console.log("recieved data: " + data);
this.distanceR = data;
});
}
Related
Im trying to clear an interval when the component is unmounted in a class based component in react. I have done some research on this and saw that in the componentWillUnmount lifecycle function, people are storing the actual function in a variable instead of just straight away clearing the interval. For example:
componentDidMount() {
const { stock } = this.props;
// Fetch data once user lands on page
this.fetchData(stock);
// Fetch data every hour
setInterval(() => {
this.fetchData(stock);
console.log('setInterval ran');
}, 3600000);
}
componentWillUnmount() {
const { stock } = this.props;
// Remove interval
const refreshFetch = clearInterval(this.fetchData(stock));
console.log('setInterval cleared');
}
async fetchData(stock) {
const data = await getAvgPriceHistory(stock);
if (data && data[stock].length) {
const dataArray = data[stock].map((arr) => {
return arr[1];
}).reverse();
this.setState({
data: dataArray,
isLoaded: true
});
} else {
// straight line if not found.
this.setState({
data: [1, 1],
isLoaded: true
});
}
console.log('Data fetched!');
}
Meanwhile, the way I am used to doing this in the componentWillUnmount function without defining a variable like so:
componentWillUnmount() {
const { stock } = this.props;
// Remove interval
clearInterval(this.fetchData(stock));
console.log('setInterval cleared');
}
Is there any benefits to doing one or the other?
setInterval return an id. You can use it with clearInterval to destroy it.
https://developer.mozilla.org/en-US/docs/Web/API/setInterval
let intervalId;
...
intervalId = setInterval(fn, time);
...
clearInterval(intervalId);
I have a problem with my React project. I have a basic SelectList with milli seconds and based on that I want to set the interval of setInterval. The thing is, it looks like it doesn't change the interval and the API calls seems too fast. The basic value is 1 minute. Here is my code:
useEffect(() => {
FetchData();
const interval = setInterval(() => {
FetchData();
}, Interval)
return() => clearInterval(interval);
},[Interval])
const handleChangeInInterval = (event) =>{
console.log("Changed interval to: ", event.target.value);
setInterval(event.target.value)
}
const FetchData = async () =>{
const resp = await axios.get("http://localhost:8080/stock/getcandle/AAPL/1")
console.log(resp);
const formattedData = formatData(resp.data.candleDataList);
console.log(formattedData);
setStockData(formattedData);
console.log("fetch called");
}
i have a react functional component.
Here is i have getData function, with this function i'm getting some data from api and then if data have i wan't to call anotherFunc();, But i wan't to do that after 3 second. I tried to put there setTimeout function but it's worked directly not wait 3 second. What i need to do?
function Hello(props) {
anotherFunc = () => {
console.log('hello');
}
const getData = () => {
let data = {
id: 1
}
axios.post(baseUrl, data).then(res => {
if (res.data) {
setTimeout(() => {
anotherFunc();
}, 3000);
}
});
}
return <h1>Something</h1>;
}
export default Hello;
I am working on a React Native app where I'm trying to call a function in setInterval to re-render component in every three seconds. But when I put the function in setInterval it returns the error this.refreshData() is not a function. Here's the code for this I'm having:
refreshData = async()=> {
await fetch('https://myapi', {
method: 'GET',
})
.then((response) => response.json())
.then((response) => {
this.setState({ tableData1: response.First })
this.setState({ tableData2: response.Special })
this.setState({ tableData3: response.Consolidation })
})
}
componentWillMount() {
const { navigation } = this.props;
this.focusListener = navigation.addListener("didFocus", () => {
var today = new Date()
var time = today.getHours()
console.log(today.getMinutes())
var weekDay = today.getDay()
if ((time >= 22) && (time <= 23 )){
if(today.getMinutes()<=30){
setInterval(function() {
this.refreshData()
}, 3000);
}
});
}
How this error can be resolved?
Use arrow function.
Try this example:
function refreshData(){
console.log("called");
}
setInterval(() => {
this.refreshData();
}, 3000);
Either bind the setTimeout/setInterval function or use Arrow function i.e
setTimeout(function() { //or setInterval(whatever you need to use)
this.refreshData()
}, 3000);
}
}).bind(this);
or
setTimeout(() => { //or setInterval(whatever you need to use)
this.refreshData();
}, 3000);
Let's say I have a checkStatus() method which is triggered after a response to an endpoint is successful. Inside this there is a setInterval like so:
checkStatus() {
setInterval(() => {
client
.query({
query,
variables,
})
.then(res => {
if (res.status) {
console.log("FINISHED!");
}
});
}, 3000);
}
Basically I am querying an endpoint every 3 seconds. Once the res.status becomes true, I want to clear the interval. The component is still there and hasn't unmounted yet.
How do I achieve this?
Just clear interval in your check condition.
Example:
checkStatus() {
const interval = setInterval(() => {
client
.query({
query,
variables,
})
.then(res => {
if (res.status) {
console.log("FINISHED!");
clearInterval(interval)
}
});
}, 3000);
}
Basically you need to assign a value to the setInterval function and clear it into your callback:
checkStatus() {
const intervale = setInterval(() => {
client
.query({
query,
variables,
})
.then(res => {
if (res.status) {
console.log("FINISHED!");
clearInterval(intervale)
}
});
}, 3000);
}
You need to first store the reference returned by setInterval and pass it to clearInterval to clear it. For example, storing the reference in a variable ref -
checkStatus() {
const ref = setInterval(() => {
client
.query({
query,
variables,
})
.then(res => {
if (res.status) {
clearInterval(ref);
console.log("FINISHED!");
}
});
}, 3000);
}
Assign a variable to the interval and clear the interval based on the condition
this.interval = setInterval(() => {
client
.query({
query,
variables,
})
.then(res => {
if (res.status) {
console.log("FINISHED!");
clearInterval(this.interval)
}
});
}, 3000);
checkStatus() {
this.interval()
}