Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add json placeholder to authors views #8

Merged
merged 2 commits into from
Jun 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 30 additions & 3 deletions src/views/AuthorDetail.jsx
Original file line number Diff line number Diff line change
@@ -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 <h2>Loading...</h2>;
}
return (
<div>
<Link to="/authors">Authors</Link>
<h2>{`Author ${id}`}</h2>
<Books />
{error ? (
<h2>Something went wrong, please try again later</h2>
) : (
<div>
<h2>{author.name}</h2>
<Books />
</div>
)}
</div>
);
}
37 changes: 30 additions & 7 deletions src/views/AuthorList.jsx
Original file line number Diff line number Diff line change
@@ -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 <h2>Loading...</h2>;
}
return (
<div>
<Link to="/">Home</Link>
<h2>Authors</h2>
{authors.map(({ id }) => <div key={id}><Link to={`/authors/${id}`}>{`Author ${id}`}</Link></div>)}
{error ? (
<h2>Something went wrong, please try again later</h2>
) : (
<div>
<h2>Authors</h2>
{authors.map(({ id, name }) => <div key={id}><Link to={`/authors/${id}`}>{name}</Link></div>)}
</div>
)}
</div>
);
}