Skip to content

Instantly share code, notes, and snippets.

@kivircik-parantez
Created January 1, 2023 12:17
Show Gist options
  • Save kivircik-parantez/8a1d597c5d3787188ff07a34e94ec4df to your computer and use it in GitHub Desktop.
Save kivircik-parantez/8a1d597c5d3787188ff07a34e94ec4df to your computer and use it in GitHub Desktop.
Data Fetch Custom Hook
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