input textの内容が変わるたびにAPIを叩きたいが、毎回叩くのは重たいので1秒に1回に制限したい、どのようなコードにする?SolidJS
You can use the debounce
function to limit the frequency of API calls. Here's an example of how to implement this in SolidJS:
- First, install the
solid-js
andsolid-js/web
packages if you haven't already:
npm install solid-js solid-js/web
- Create a
debounce
function:
function debounce(fn, delay) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, args), delay);
};
}
- Use the
debounce
function in your SolidJS component:
import { createEffect, createSignal } from "solid-js";
function App() {
const [inputText, setInputText] = createSignal("");
const [result, setResult] = createSignal("");
const handleInputChange = debounce(async (value) => {
// Call your API here
const response = await fetch(`https://your-api.com?input=${value}`);
const data = await response.json();
setResult(data.result);
}, 1000);
createEffect(() => {
handleInputChange(inputText());
});
return (
<>
<input
type="text"
value={inputText()}
onInput={(e) => setInputText(e.target.value)}
/>
<div>{result()}</div>
</>
);
}
export default App;
In this example, the handleInputChange
function is debounced with a 1-second delay. The function will only be called once every second, even if the input text changes more frequently.