Last active
January 2, 2023 21:52
-
-
Save alperkilickaya/ef58301c1ff244d3233a8db616480442 to your computer and use it in GitHub Desktop.
Make http request in React useEffect hook after 0.5 seconds later stopping keystroke by using setTimeout function and useRef hook.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useState, useEffect, useRef } from 'react'; | |
| import Card from '../UI/Card'; | |
| import './Search.css'; | |
| const Search = React.memo(props => { | |
| const { onLoadIngredients } = props; | |
| const [enteredFilter, setEnteredFilter] = useState(''); | |
| const inputRef = useRef(); | |
| useEffect(() => { | |
| const timer = setTimeout(() => { | |
| // technically compare old input value (state itself) and the real input value by using ref. | |
| // if both are same then we can say user paused typing and make htttp request | |
| if (enteredFilter === inputRef.current.value) { | |
| const query = | |
| enteredFilter.length === 0 | |
| ? '' | |
| : `?orderBy="title"&equalTo="${enteredFilter}"`; | |
| fetch( | |
| API_URL + query | |
| ) | |
| .then(response => response.json()) | |
| .then(responseData => { | |
| const loadedIngredients = []; | |
| for (const key in responseData) { | |
| loadedIngredients.push({ | |
| id: key, | |
| title: responseData[key].title, | |
| amount: responseData[key].amount | |
| }); | |
| } | |
| onLoadIngredients(loadedIngredients); | |
| }); | |
| } | |
| }, 500); | |
| // clears timer. This ensures that we always have only one ongoing timer. | |
| // clears reduntant timers in memory. | |
| return () => { | |
| clearTimeout(timer); | |
| }; | |
| }, [enteredFilter, onLoadIngredients, inputRef]); | |
| return ( | |
| <section className="search"> | |
| <Card> | |
| <div className="search-input"> | |
| <label>Filter by Title</label> | |
| <input | |
| ref={inputRef} | |
| type="text" | |
| value={enteredFilter} | |
| onChange={event => setEnteredFilter(event.target.value)} | |
| /> | |
| </div> | |
| </Card> | |
| </section> | |
| ); | |
| }); | |
| export default Search; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment