Created
March 6, 2020 16:27
-
-
Save faahmad/fe28d33b7914610cb531c9cfb33b729f to your computer and use it in GitHub Desktop.
Opinionated React 3: State Management
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export const MovieList: React.FC = () => { | |
| const [isLoading, setIsLoading] = React.useState<boolean>(true); | |
| const [movies, setMovies] = React.useState<Movie[]>([]); | |
| const [error, setError] = React.useState<string>(""); | |
| const handleFetchMovies = () => { | |
| setIsLoading(true); // π’ | |
| setError(""); // π’ | |
| return MovieService.fetchInitialMovies() | |
| .then(initialMovies => { | |
| setMovies(initialMovies); | |
| setIsLoading(false); // π’ | |
| }) | |
| .catch(err => { | |
| setError(err.message); // π’ | |
| setIsLoading(false); // π’ | |
| }); | |
| }; | |
| React.useEffect(() => { | |
| handleFetchMovies(); | |
| }, []); | |
| if (isLoading) { | |
| return <div>Loading movies...</div>; | |
| } | |
| if (error !== "") { | |
| return ( | |
| <div> | |
| <p className="text-red">{error}</p> | |
| <button onClick={handleFetchMovies}>Try again</button> | |
| </div> | |
| ); | |
| } | |
| return ( | |
| <ul> | |
| {movies.map(movie => ( | |
| <li key={movie.id}>{movie.title}</li> | |
| ))} | |
| </ul> | |
| ); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment