Skip to content

Instantly share code, notes, and snippets.

@willprice76
Last active May 1, 2020 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willprice76/1942420cd7886d86981d052bafa65275 to your computer and use it in GitHub Desktop.
Save willprice76/1942420cd7886d86981d052bafa65275 to your computer and use it in GitHub Desktop.
Managing React component state with useState
export const RecipeList = () => {
//component state
const [isLoading, setIsLoading] = useState(true);
const [loadingFailed, setLoadingFailed] = useState(false);
const [loadingError, setLoadingError] = useState("");
const [recipes, setRecipes] = useState<Recipe[]>();
//load data
useEffect(() => {
setIsLoading(true);
setLoadingFailed(false);
api.getRecipes().then(response => {
setRecipes(response.data);
}).catch((error: string) => {
setLoadingFailed(true);
setLoadingError(error);
}).finally(() => {
setIsLoading(false);
});
}, []);
return (
<div>
{isLoading && "Loading..."}
{loadingFailed && "Error: " + loadingError}
{!isLoading && !loadingFailed && recipes && (
<ul>
{recipes.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
)}
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment