Home > Back-end >  Call an API 2 secs after user has key some values
Call an API 2 secs after user has key some values

Time:11-07

I am wondering if there is a way to call an API in few secs after user has entered the values.

This logic is implemented in Saga middleware where takeLatest keyword is being used to take the latest value and make an api call.

import { takeLatest} from 'redux-saga/effects';

function* watchTheRequest() {
    const watcher = yield takeLatest('SOME_TYPE', callMySaga);
    yield take(LOCATION_CHANGE);
    yield cancel(watcher);
}

I am trying to implement the same in React UseEffect hook.

Requirement is: Once users stops typing, make an API call.

const [search, setSearch] = useState("")
useEffect(() => {
    //wait for user to stop updating the search.
    // call API.
}, [search])

Not sure if I need to use either of the following to achieve this task

var intervalID = setInterval(alert, 1000); 
setTimeout(alert, 1000);

CodePudding user response:

It's called Debounce technique, you can check it out here

You can try with this implementation

const timeoutId = useRef();
const [searchTerm, setSearchTerm] = useState('');

const onSearchChange = (newSearchTerm) => {
  // Wait for 300ms after users stop typing
  // then dispatch to get the suggestions
  clearTimeout(timeoutId.current);

  timeoutId.current = setTimeout(() => {
    if (newSearchTerm.length >= 2) {
      dispatch(getSuggestions(newSearchTerm));
    }
  }, 300);
};

CodePudding user response:

That's called 'debounce' probably. Minimalistic implementation with useEffect:

const [search, setSearch] = useState("");

const toBeCalled = () => {
 // call your API here
}

useEffect(() => {
   const timer = setTimeout(toBeCalled, 1000);
   return () => clearTimeout(timer);
}, [search]);

CodePudding user response:

if you are using React 18 you can use useDeferredValue

  const [search, setSearch] = useState("")
  const deferredSearch = useDeferredValue(search)
  useEffect(() => {
     //wait for user to stop updating the search.
     // call API.
  }, [deferredSearch])
  ......

}

Check this blog to get more information

  • Related