Skip to content

Commit

Permalink
Adding Search Functionality to the Gallery
Browse files Browse the repository at this point in the history
  • Loading branch information
lelouchB committed Nov 13, 2020
1 parent 4d4bb45 commit 91c7493
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 12 deletions.
11 changes: 11 additions & 0 deletions lib/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,14 @@ export const getCuratedPhotos = async () => {
const responseJson = await res.json();
return responseJson.photos;
};

export const getQueryPhotos = async (query) => {
const res = await fetch(`https://api.pexels.com/v1/search?query=${query}`, {
headers: {
Authorization: API_KEY,
},
});
const responseJson = await res.json();
return responseJson.photos;
};

83 changes: 71 additions & 12 deletions pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,43 @@
import React, { useState } from "react";
import Head from "next/head";
import Image from "next/image";
import { Box, Container, Text, Wrap, WrapItem } from "@chakra-ui/core";
import { getCuratedPhotos } from "../lib/api";
import {
Box,
Container,
Text,
Wrap,
WrapItem,
Input,
IconButton,
InputRightElement,
InputGroup,
useToast,
} from "@chakra-ui/core";
import { SearchIcon } from "@chakra-ui/icons";
import { getCuratedPhotos, getQueryPhotos } from "../lib/api";

export default function Home({ data }) {
const [photos, setPhotos] = useState(data);
const [query, setQuery] = useState("");
const toast = useToast();
const handleSubmit = async (e) => {
await e.preventDefault();
if (query == "") {
toast({
title: "Error.",
description: "Empty Search",
status: "error",
duration: 9000,
isClosable: true,
position: "top",
});
} else {
const res = await getQueryPhotos(query);
await setPhotos(res);
await setQuery("");
}
};

return (
<div>
<Head>
Expand All @@ -25,19 +57,46 @@ export default function Home({ data }) {
>
NextJS Image Gallery
</Text>
<form onSubmit={handleSubmit}>
<InputGroup pb="1rem">
<Input
placeholder="Search for Apple"
variant="ghost"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>

<InputRightElement
children={
<IconButton
aria-label="Search"
icon={<SearchIcon />}
bg="pink.400"
color="white"
onClick={handleSubmit}
/>
}
/>
</InputGroup>
</form>
</Container>
<Wrap px="1rem" spacing={4} justify="center">
{photos.map((pic) => (
<WrapItem
key={pic.id}
boxShadow="base"
rounded="20px"
overflow="hidden"
bg="white"
_hover={{ boxShadow: "dark-lg" }}
>
<Image src={pic.src.portrait} height={600} width={400} alt={pic.url} />
</WrapItem>
<WrapItem
key={pic.id}
boxShadow="base"
rounded="20px"
overflow="hidden"
bg="white"
_hover={{ boxShadow: "dark-lg" }}
>
<Image
src={pic.src.portrait}
height={600}
width={400}
alt={pic.url}
/>
</WrapItem>
))}
</Wrap>
</Box>
Expand Down

0 comments on commit 91c7493

Please sign in to comment.