import * as React from 'react';
import { CharacterType, fetchCharacter } from './characters';
import { Loading } from './Loading';
import { CharacterInformation } from './CharacterInformation';
const Application = () => {
// we define the character type to be either CharacterType or null
const [character, setCharacter] = React.useState<CharacterType | null>(null);
const [loading, setLoading] = React.useState(true);
React.useEffect(() => {
setTimeout(() => {
fetchCharacter().then(c => { setCharacter(c); setLoading(false) });
}, 1000);
}, []);
// we cannot just simply using loading or !character to decide whether render charaterInformation
// you can think that !character doesnt make typescript know the character is not null
// so a common way to fix this is show them seperately
return <main>
{loading && <Loading />}
{ character && <CharacterInformation character={character} /> }
</main>;
};
export default Application;
see more