When trying to use _.debounce(fn, wait); to invoke an apollo-client useLazyQuery(...) call it debounces the query the first time and then invokes the query function, but after that it keeps invoking the query with every change without any debouncing.
However, if I'm using a console.log(...) instead of the useLazyQuery(...) call it would work perfectly.
Works the first time but then calls the function immediately without any debouncing:
const [value, setValue] = useState('');
const [search, { loading, data }] = useLazyQuery(SEARCH_QUERY, { variables: { searchString: value } });
const debouncer = React.useCallback(_.debounce(search, 1500), []);
...
<call to debouncer() with onChange event>
Works perfectly every time:
const [value, setValue] = useState('');
const [search, { loading, data }] = useLazyQuery(SEARCH_QUERY, { variables: { searchString: value } });
const debouncer = React.useCallback(_.debounce(val => (console.log(val)), 1500), []);
...
<call to debouncer() with onChange event>
For this problem, you don't even need a state; simplified versrion:
import { useCallback } from 'react';
import { useLazyQuery } from '@apollo/client';
import _ from 'lodash';
function App() {
const [search, { loading, data }] = useLazyQuery(SEARCH_QUERY);
const debouncer = useCallback(_.debounce(search, 1000), []);
return (
<input
type='text'
onChange={e => debouncer({ variables: { code: e.target.value } })}
/>
);
}