Created
January 1, 2023 12:17
-
-
Save kivircik-parantez/8a1d597c5d3787188ff07a34e94ec4df to your computer and use it in GitHub Desktop.
Data Fetch Custom Hook
This file contains 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
function SearchResults({ query }) { | |
const [page, setPage] = useState(1); | |
const params = new URLSearchParams({ query, page }); | |
const results = useData(`/api/search?${params}`); | |
function handleNextPageClick() { | |
setPage(page + 1); | |
} | |
// ... | |
} | |
function useData(url) { | |
const [data, setData] = useState(null); | |
useEffect(() => { | |
let ignore = false; | |
fetch(url) | |
.then(response => response.json()) | |
.then(json => { | |
if (!ignore) { | |
setData(json); | |
} | |
}); | |
return () => { | |
ignore = true; | |
}; | |
}, [url]); | |
return data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment