Skip to content

Commit

Permalink
Merge pull request #8 from IIC2513-2021-1/feat/jsonplaceholder-connec…
Browse files Browse the repository at this point in the history
…tion

Add json placeholder to authors views
  • Loading branch information
meretamal authored Jun 28, 2021
2 parents 0a754c0 + 0872915 commit dbfbfbd
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 10 deletions.
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>
);
}

0 comments on commit dbfbfbd

Please sign in to comment.