Skip to content

Instantly share code, notes, and snippets.

@faahmad
Created March 6, 2020 16:27
Show Gist options
  • Select an option

  • Save faahmad/fe28d33b7914610cb531c9cfb33b729f to your computer and use it in GitHub Desktop.

Select an option

Save faahmad/fe28d33b7914610cb531c9cfb33b729f to your computer and use it in GitHub Desktop.
Opinionated React 3: State Management
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