L
L
lexstile2022-03-28 18:22:19
React
lexstile, 2022-03-28 18:22:19

How to organize a debounce effect in conjunction with react-query?

How can I refuse the second state? (clientName1, setClietName1)
What happens - the user enters the last name and a second after he stopped, we make a request.
Component:

export const ClientSelectField = ({ ...props }: Props) => {
  const [clientName, setClietName] = useState('');
  const [clientName1, setClietName1] = useState('');
  const { data, isLoading } = useQuery(['task-client-list', clientName1], () => loadClientList(clientName));

  const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => setClietName(event.target.value);

  useDebouncedEffect(() => setClietName1(clientName), [clientName], 1000);

  return (
    <SearchSelectField {...props} isLoading={isLoading} onInputChange={handleInputChange}>
      {data?.map((client) => (
        <Option key={client.id} value={client.id.toString()} renderChip={() => client.fullName}>
          {client.fullName}
        </Option>
      ))}
    </SearchSelectField>
  );
};

Call:
<ClientSelectField
            name="clientId"
            label="Клиент"
            placeholder="Начните вводить фамилию"
            value={filters.clientId || ''}
            onChange={handleChangeSelectField}
            data-test-id={getDataTestId(...dataTestKeys, 'client')}
          />

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
wonderingpeanut, 2022-03-29
@lexstile

I don't see a way to get rid of the second state. I only see how to replace the second input state with a boolean state

const [shouldCallApi, setShouldCallApi] = useState(false);
useEffect(() => {
  const timerId = setTimeout(() => {
    setShouldCallApi(true);
  }, 1000);
  return () => clearTimeout(timerId);
}, [clientName]);
const { data, isLoading } = useQuery(['task-client-list', clientName1], () => loadClientList(clientName),{enabled: shouldCallApi});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question