Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.4 kB
1
Indexable
Never
import _debounce from 'lodash/debounce';
import { Input } from '@chakra-ui/react';

const clients = [
  { code: 1, name: 'Client A' },
  { code: 2, name: 'Client B' },
  // ... and so on, up to client code 100
];

const fetchSuggestions = async (query) => {
  // Simulate API call delay with setTimeout
  return new Promise((resolve) => {
    setTimeout(() => {
      const filteredClients = clients.filter((client) =>
        client.name.toLowerCase().includes(query.toLowerCase())
      );
      resolve(filteredClients);
    }, 300);
  });
};

const debouncedFetchSuggestions = _debounce(fetchSuggestions, 300);

const MyInputWithSuggestions = () => {
  const [inputValue, setInputValue] = React.useState('');
  const [suggestions, setSuggestions] = React.useState([]);

  const handleInputChange = (value) => {
    setInputValue(value);
    debouncedFetchSuggestions(value).then((data) => {
      setSuggestions(data);
    });
  };

  return (
    <div>
      <Input
        type="text"
        value={inputValue}
        onChange={(e) => handleInputChange(e.target.value)}
        placeholder="Start typing to see suggestions..."
      />
      {/* Render the suggestions */}
      <ul>
        {suggestions.map((client) => (
          <li key={client.code}>{client.name}</li>
        ))}
      </ul>
    </div>
  );
};