I currently have an input field that is meant to trigger an api call when an 11 digit number is input. How do I delay it from making the call until all 11 digits are typed
Something simple like this should do the trick.
const callAPI = (value) =>{
if(value.length === 11){
console.log("Call API")
}
}
<input type="text" oninput="callAPI(value)"/>
You could make the component be a controlled component, and perform the check to trigger the API call in the input's change handler.
Here is a code sample.
import { useState } from 'react';
const MyComponent = () => {
const [inputValue, setInputValue] = useState(0);
const handleChange = (e) => {
setInputValue(e.target.value);
if (inputValue.length === 11) {
// code to trigger API call
}
}
return (
<input value={inputValue} onChange={(e) => handleChange(e)} />
);
}
Explanation:
A controlled component controls the value of the input element using the React state itself.
Import the state hook.
import { useState } from 'react';
Use a state hook for the input's value.
const [inputValue, setInputValue] = useState(0);
Set the input's value attribute to equal to the state.
<input value={inputValue} />
Add an onChange event handler to the input element.
<input value={inputValue} onChange={handleChange} />
Create the event handler.
const handleChange = (e) => { //code for event handler }
Whenever you type in the input field, this will trigger the onChange event and run the event handler handleChange.
In the event handler, first update the state using the user input.
setInputValue(e.target.value);
Then, check the length of the input value, and trigger the call accordingly.
if (inputValue.length === 11) { // code to trigger API call }
If you are making a controlled form it is easy to check when you update the value.
import { useState } from "react";
export default function Form() {
const [inputValue, setInputValue] = useState("");
function handelChange(event) {
setInputValue(event.target.value);
// If the length is 11 characters do something
if (inputValue.length === 11) {
document.body.style.backgroundColor = "black";
} else {
// Otherwise do something else
document.body.style.backgroundColor = "white";
}
}
return (
<input
type="text"
onChange={(e) => {
handelChange(e);
}}
value={inputValue}
/>
);
}