Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Container } from "@material-ui/core";
- import PhotosList from "./components/PhotosList";
- import SearchForm from "./components/SearchForm";
- import React, { useState, useEffect } from "react";
- const initUrl =
- "https://api.unsplash.com/photos/";
- const searchUrl =
- "https://api.unsplash.com/search/photos/page=1&query=";
- function App() {
- const [page, setPage] = useState(1);
- const [isLoading, setIsLoading] = useState(true);
- const [isSearching, setIsSearching] = useState(false);
- const [searchValue, setSearchValue] = useState("");
- const [value, setValue] = useState("");
- const [photos, setPhotos] = useState([]);
- const getPhotosFromInitUrl = async () => {
- setIsLoading(true);
- if (!isSearching) {
- const response = await fetch(`${initUrl}&page=${page}`);
- const data = await response.json();
- setPhotos((oldPhotos) => {
- return [...oldPhotos, ...data];
- });
- } else {
- const response = await fetch(`${searchUrl}${searchValue}`);
- const data = await response.json();
- setPhotos(data.results);
- }
- setIsLoading(false);
- };
- const handleSubmit = (e) => {
- e.preventDefault();
- setIsSearching(true);
- setSearchValue(value);
- };
- useEffect(() => {
- getPhotosFromInitUrl();
- }, [searchValue, page]);
- useEffect(() => {
- const event = window.addEventListener("scroll", () => {
- if (
- (isLoading && window.innerHeight + window.scrollY) >=
- document.body.scrollHeight - 2
- ) {
- setPage((oldPage) => {
- return oldPage + 1;
- });
- }
- });
- return () => window.removeEventListener("scroll", event);
- }, []);
- return (
- <Container component="main" className="App">
- <SearchForm
- value={value}
- setValue={setValue}
- handleSubmit={handleSubmit}
- />
- <PhotosList isLoading={isLoading} photos={photos} />
- </Container>
- );
- }
- export default App;
Advertisement
Add Comment
Please, Sign In to add comment