Last active
January 3, 2021 18:01
-
-
Save markninja96/0e8abbf9e230278a6397ec050a900e58 to your computer and use it in GitHub Desktop.
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
| //App.js | |
| import { useState, useEffect } from "react"; | |
| import useInfiniteScroll from "./useInfiniteScroll"; | |
| import axios from "axios"; | |
| const App = () => { | |
| //we change here | |
| const [Items, setItems] = useState([]); | |
| const [isFetching, setIsFetching] = useState(false); | |
| //setting tha initial page | |
| const [page, setPage] = useState(0); | |
| //we need to know if there is more data | |
| const [HasMore, setHasMore] = useState(true); | |
| const [lastElementRef] = useInfiniteScroll( | |
| HasMore ? loadMoreItems : () => {}, | |
| isFetching | |
| ); | |
| //on initial mount | |
| useEffect(() => { | |
| loadMoreItems(); | |
| }, []); | |
| function loadMoreItems() { | |
| setIsFetching(true); | |
| //using axios to access the third party API | |
| axios({ | |
| method: "GET", | |
| url: "https://jsonplaceholder.typicode.com/albums", | |
| params: { _page: page, _limit: 40 }, | |
| }) | |
| .then((res) => { | |
| setItems((prevTitles) => { | |
| return [...new Set([...prevTitles, ...res.data.map((b) => b.title)])]; | |
| }); | |
| setPage((prevPageNumber) => prevPageNumber + 1); | |
| setHasMore(res.data.length > 0); | |
| setIsFetching(false); | |
| }) | |
| .catch((e) => { | |
| console.log(e); | |
| }); | |
| } | |
| return ( | |
| <div> | |
| {Items.map((item, index) => { | |
| if (Items.length === index + 1) { | |
| return ( | |
| //referencing the last item to be watched by the observer | |
| <div ref={lastElementRef} key={index}> | |
| {item} - <b>last</b> | |
| </div> | |
| ); | |
| } else { | |
| return <div key={index}>{item}</div>; | |
| } | |
| })} | |
| {isFetching && <p>Fetching items...</p>} | |
| </div> | |
| ); | |
| }; | |
| export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment