'having a function run every ten seconds or when an input changes
I have a simple react app where a user inputs a quantity and an api call is made to convert that value into an equivalent amount of a very unstable cryptocurrency, and that converted value is displayed on the screen.
Crucially, I want the converted value to be updated every ten seconds or when a user changes the input value.
I'm confused as to how to implement this. Any advice?
Solution 1:[1]
I don't know react, but in native JS it's pretty simple. Here's some code that sets your timer then clears and resets when you call an input change. Hope this is easily adaptable to react!
function cryptoTimer() {
this.value = null
this.timer = null
this.getValue = () => {
this.value = "some api response"
console.log(this.value)
}
this.startTimer = () => {
this.timer = setInterval(() => { this.getValue() }, 10000)
}
this.clearTimer = () => {
clearInterval(this.timer)
}
this.inputChange = (elem) => {
console.log('input changed, value is '+elem.value)
this.clearTimer()
this.init()
}
this.init = () => {
this.getValue()
this.startTimer()
}
this.init()
}
var timer = new cryptoTimer
<!-- some input on change action -->
<input onkeyup="timer.inputChange(this)" type="text" />
Solution 2:[2]
Here is an example
import React from "react";
export function App() {
// Used to store the intervalId
const timerRef = React.useRef();
// Used to store the value in the input element
const inputRef = React.useRef("");
// This is for storing the transformed value you get from API
const [transformedValue, setTransformedValue] = React.useState("");
// In this function, you can make the request to the API and update
// the transformed value. Remember to reset the interval.
const transformValue = async () => {
const input = inputRef.current;
// Invoke your api instead
const randomTransformation = `${input} ${new Date().toLocaleTimeString()}`;
setTransformedValue(randomTransformation);
resetInterval();
};
// This will just reset the interval
const resetInterval = () => {
if (timerRef.current) {
clearInterval(timerRef.current);
}
timerRef.current = setInterval(transformValue, 10 * 1000);
};
return (
<div className="container">
<label htmlFor="input">Input</label>
<input
id="input"
type="text"
value={inputRef.current}
onChange={(e) => {
inputRef.current = e.target.value;
transformValue();
}}
/>
<p>Transformed Value: {transformedValue}</p>
</div>
);
}
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 | Spencer May |
| Solution 2 | Vighnesh Raut |
