weikee94 / react-ts

react with typescript
0 stars 0 forks source link

Setting State without a Default Value #3

Open weikee94 opened 3 years ago

weikee94 commented 3 years ago

see more

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;