Forked from an inaccessible project.
-
Thor-Herman Van Eggelen authoredThor-Herman Van Eggelen authored
usePoetry.tsx 1.18 KiB
import React, { useEffect, useState } from 'react';
const poets = [
"Walt Whitman",
"William Shakespeare",
"Alexander Pope",
"Edgar Allan Poe",
"Emily Bronte",
"John Keats",
"Oscar Wilde",
"William Wordsworth",
"Charlotte Bronte",
"Eliza Cook"
]
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
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); // Update the state
setTitle(data[0].title);
setAuthor(data[0].author);
});
}, [poetId]);
return [title, poem, author] as const;
}
export default usePoetry;