Guest User

Untitled

a guest
Feb 24th, 2021
380
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Container } from "@material-ui/core";
  2. import PhotosList from "./components/PhotosList";
  3. import SearchForm from "./components/SearchForm";
  4. import React, { useState, useEffect } from "react";
  5.  
  6. const initUrl =
  7.   "https://api.unsplash.com/photos/";
  8.  
  9. const searchUrl =
  10.   "https://api.unsplash.com/search/photos/page=1&query=";
  11.  
  12. function App() {
  13.   const [page, setPage] = useState(1);
  14.   const [isLoading, setIsLoading] = useState(true);
  15.   const [isSearching, setIsSearching] = useState(false);
  16.   const [searchValue, setSearchValue] = useState("");
  17.   const [value, setValue] = useState("");
  18.   const [photos, setPhotos] = useState([]);
  19.  
  20.   const getPhotosFromInitUrl = async () => {
  21.     setIsLoading(true);
  22.     if (!isSearching) {
  23.       const response = await fetch(`${initUrl}&page=${page}`);
  24.       const data = await response.json();
  25.       setPhotos((oldPhotos) => {
  26.         return [...oldPhotos, ...data];
  27.       });
  28.     } else {
  29.       const response = await fetch(`${searchUrl}${searchValue}`);
  30.       const data = await response.json();
  31.       setPhotos(data.results);
  32.     }
  33.     setIsLoading(false);
  34.   };
  35.  
  36.   const handleSubmit = (e) => {
  37.     e.preventDefault();
  38.     setIsSearching(true);
  39.     setSearchValue(value);
  40.   };
  41.  
  42.   useEffect(() => {
  43.     getPhotosFromInitUrl();
  44.   }, [searchValue, page]);
  45.  
  46.   useEffect(() => {
  47.     const event = window.addEventListener("scroll", () => {
  48.       if (
  49.         (isLoading && window.innerHeight + window.scrollY) >=
  50.         document.body.scrollHeight - 2
  51.       ) {
  52.         setPage((oldPage) => {
  53.           return oldPage + 1;
  54.         });
  55.       }
  56.     });
  57.     return () => window.removeEventListener("scroll", event);
  58.    
  59.   }, []);
  60.  
  61.   return (
  62.     <Container component="main" className="App">
  63.       <SearchForm
  64.         value={value}
  65.         setValue={setValue}
  66.         handleSubmit={handleSubmit}
  67.       />
  68.       <PhotosList isLoading={isLoading} photos={photos} />
  69.     </Container>
  70.   );
  71. }
  72.  
  73. export default App;
  74.  
Advertisement
Add Comment
Please, Sign In to add comment