2022-06-25 14:23:41 -05:00
|
|
|
import React, { useEffect, useState } from 'react';
|
2022-06-25 10:30:21 -05:00
|
|
|
|
|
|
|
|
import Greeting from '../components/greeting';
|
2022-06-25 14:23:41 -05:00
|
|
|
import CardHolder from '../components/cardHolder';
|
|
|
|
|
import CharacterCard from '../components/characterCard';
|
2022-06-25 23:39:33 -05:00
|
|
|
import Loading from '../components/loading';
|
2022-06-28 18:49:06 -05:00
|
|
|
import LoadingError from '../components/loadingError';
|
2022-06-25 14:23:41 -05:00
|
|
|
|
|
|
|
|
import CharacterService from '../services/characterService';
|
|
|
|
|
const characterService = new CharacterService();
|
2022-06-24 23:23:06 -05:00
|
|
|
|
|
|
|
|
export default function Home() {
|
2022-06-25 14:23:41 -05:00
|
|
|
|
|
|
|
|
const [characters, setCharacters] = useState([]);
|
2022-06-28 18:49:06 -05:00
|
|
|
const [errorMessage, setErrorMessage] = useState(null);
|
2022-06-25 14:23:41 -05:00
|
|
|
|
|
|
|
|
const getCharacters = async () => {
|
|
|
|
|
|
|
|
|
|
const res = await characterService.getCharacters();
|
|
|
|
|
|
2022-06-28 18:49:06 -05:00
|
|
|
if (!res.ok) {
|
|
|
|
|
|
|
|
|
|
return setErrorMessage('Failed to load characters.');
|
|
|
|
|
|
|
|
|
|
}
|
2022-06-25 23:39:33 -05:00
|
|
|
|
2022-06-25 14:23:41 -05:00
|
|
|
const characters = await res.json();
|
|
|
|
|
|
|
|
|
|
return setCharacters(characters);
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
2022-06-28 18:49:06 -05:00
|
|
|
|
2022-06-25 14:23:41 -05:00
|
|
|
getCharacters();
|
2022-06-28 18:49:06 -05:00
|
|
|
|
2022-06-25 14:23:41 -05:00
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
const getCharacterCards = () => {
|
|
|
|
|
|
|
|
|
|
return characters.map(character => {
|
|
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
|
|
|
|
|
<CharacterCard
|
|
|
|
|
character={character}
|
2022-06-28 18:49:06 -05:00
|
|
|
key={character.id}
|
2022-06-25 14:23:41 -05:00
|
|
|
/>
|
|
|
|
|
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
2022-06-28 18:49:06 -05:00
|
|
|
const handleTryAgain = async () => {
|
|
|
|
|
|
|
|
|
|
if (errorMessage === 'Failed to load characters.') return await getCharacters();
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
2022-06-24 23:23:06 -05:00
|
|
|
return (
|
|
|
|
|
<>
|
2022-06-25 23:39:33 -05:00
|
|
|
<Greeting />
|
2022-06-26 11:49:03 -05:00
|
|
|
|
2022-06-25 14:59:59 -05:00
|
|
|
{characters.length > 0 ?
|
2022-06-26 11:49:03 -05:00
|
|
|
|
2022-06-25 23:39:33 -05:00
|
|
|
<CardHolder>
|
2022-06-26 11:49:03 -05:00
|
|
|
|
2022-06-25 23:39:33 -05:00
|
|
|
{getCharacterCards()}
|
2022-06-26 11:49:03 -05:00
|
|
|
|
2022-06-25 23:39:33 -05:00
|
|
|
</CardHolder>
|
2022-06-26 11:49:03 -05:00
|
|
|
|
2022-06-28 18:49:06 -05:00
|
|
|
: errorMessage ?
|
|
|
|
|
|
|
|
|
|
<LoadingError
|
|
|
|
|
message={errorMessage}
|
|
|
|
|
onClick={handleTryAgain}
|
|
|
|
|
/>
|
|
|
|
|
|
2022-06-25 23:39:33 -05:00
|
|
|
: <Loading />}
|
2022-06-24 23:23:06 -05:00
|
|
|
</>
|
|
|
|
|
);
|
|
|
|
|
}
|