Last active
May 1, 2020 20:14
-
-
Save willprice76/1942420cd7886d86981d052bafa65275 to your computer and use it in GitHub Desktop.
Managing React component state with useState
This file contains 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 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