Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Thank you @sergiodxa that was exactly what I was looking for to spin a few ideas into my mind! #24

Open
luke-hanwook opened this issue Oct 26, 2022 · 0 comments

Comments

@luke-hanwook
Copy link
Owner

    Thank you @sergiodxa that was exactly what I was looking for to spin a few ideas into my mind!

My implementation for others:

import useSWR from 'swr';

import { useDebounce } from '../../../utils/hooks';
...
// inside my component render method
  const [search, setSearch] = useState('');
  const debouncedSearch = useDebounce(search, 1000);
const { data: res, isValidating } = useSWR(
    () =>
      debouncedSearch ? `/api/suggestion?value=${debouncedSearch}` : null,
    Api.fetcher,
  );
...
// useDebounce.js
import { useState, useEffect } from 'react';

export default function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
}

Originally posted by @watadarkstar in vercel/swr#110 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant