From c1fb47a1572a340447350bca7758afc2816788a0 Mon Sep 17 00:00:00 2001 From: meretamal Date: Sun, 27 Jun 2021 15:11:17 -0400 Subject: [PATCH 1/2] feat(author-list): add jsonplaceholder request to author list view --- src/views/AuthorList.jsx | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/src/views/AuthorList.jsx b/src/views/AuthorList.jsx index 92776c9..f8c7bfd 100644 --- a/src/views/AuthorList.jsx +++ b/src/views/AuthorList.jsx @@ -1,17 +1,40 @@ -import React from 'react'; +import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; export default function AuthorList() { - const authors = [ - { id: 1 }, - { id: 2 }, - ]; + const [authors, setAuthors] = useState([]); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(false); + useEffect(() => { + setLoading(true); + fetch('https://jsonplaceholder.typicode.com/users') + .then((response) => { + if (response.status !== 200) { + setError(true); + return []; + } + return response.json(); + }) + .then(setAuthors) + .catch(() => setError(true)) + .finally(() => setLoading(false)); + }, []); + + if (loading) { + return

Loading...

; + } return (
Home -

Authors

- {authors.map(({ id }) =>
{`Author ${id}`}
)} + {error ? ( +

Something went wrong, please try again later

+ ) : ( +
+

Authors

+ {authors.map(({ id, name }) =>
{name}
)} +
+ )}
); } From 087291524b68308bf5c6c3b9c3209d26b0ee19ab Mon Sep 17 00:00:00 2001 From: meretamal Date: Sun, 27 Jun 2021 15:11:39 -0400 Subject: [PATCH 2/2] feat(author-detail): add jsonplaceholder request to author detail view --- src/views/AuthorDetail.jsx | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/src/views/AuthorDetail.jsx b/src/views/AuthorDetail.jsx index b843e06..3da098e 100644 --- a/src/views/AuthorDetail.jsx +++ b/src/views/AuthorDetail.jsx @@ -1,15 +1,42 @@ -import React from 'react'; +import React, { useState, useEffect } from 'react'; import { Link, useParams } from 'react-router-dom'; import Books from '../components/Books'; export default function AuthorDetail() { const { id } = useParams(); + const [author, setAuthor] = useState({}); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(false); + useEffect(() => { + setLoading(true); + fetch(`https://jsonplaceholder.typicode.com/users/${id}`) + .then((response) => { + if (response.status !== 200) { + setError(true); + return {}; + } + return response.json(); + }) + .then(setAuthor) + .catch(() => setError(true)) + .finally(() => setLoading(false)); + }, []); + + if (loading) { + return

Loading...

; + } return (
Authors -

{`Author ${id}`}

- + {error ? ( +

Something went wrong, please try again later

+ ) : ( +
+

{author.name}

+ +
+ )}
); }