Skip to content

Instantly share code, notes, and snippets.

@nishio

nishio/a.md Secret

Created March 30, 2023 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nishio/7b413915cf6ad7cf1aaf3c75d06ca902 to your computer and use it in GitHub Desktop.
Save nishio/7b413915cf6ad7cf1aaf3c75d06ca902 to your computer and use it in GitHub Desktop.

2: user

input textの内容が変わるたびにAPIを叩きたいが、毎回叩くのは重たいので1秒に1回に制限したい、どのようなコードにする?SolidJS

3: assistant

You can use the debounce function to limit the frequency of API calls. Here's an example of how to implement this in SolidJS:

  1. First, install the solid-js and solid-js/web packages if you haven't already:
npm install solid-js solid-js/web
  1. Create a debounce function:
function debounce(fn, delay) {
  let timeout;
  return function (...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn.apply(this, args), delay);
  };
}
  1. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment