Newer
Older
import React, { useEffect, useState } from 'react';
const poets = [
"Walt Whitman",
"Alexander Pope",
"George Gordon",
"Emily Dickinson",
"William Morris",
"Sidney Lanier",
"Robert Herrick",
type dataResponse = {
title: string;
author: string;
lines: Array<string>;
linecount: number;
const usePoetry = (poetId: number) => { // Custom hook for retrieving poetry. Enter id and it will retrieve the corresponding poem
const [poem, setPoem] = useState<Array<string> | null>(null); // The poem itself. Initialized as null
const [title, setTitle] = useState("Loading...");
const [author, setAuthor] = useState("Loading...");
useEffect(() => { // Will run every time the Id changes
setPoem(["Loading..."]);
setTitle("Loading...");
setAuthor("Loading...");
fetch(`https://poetrydb.org/author,poemcount,linecount/${poets[poetId]};1;4`) // GET request to poetryDb
.then((response) => response.json()) // Convert response to json
.then((data: Array<dataResponse>) => {
setPoem(data[0].lines.slice(0,4)); // Update the state
setTitle(data[0].title);
setAuthor(data[0].author);
});
}, [poetId]);
return [title, poem, author] as const;
export default usePoetry;