Skip to content

Instantly share code, notes, and snippets.

@nguyenit67
Last active May 3, 2022 17:05
Show Gist options
  • Save nguyenit67/631d65baff7e7ce172666331c6c33d21 to your computer and use it in GitHub Desktop.
Save nguyenit67/631d65baff7e7ce172666331c6c33d21 to your computer and use it in GitHub Desktop.
manual hooks for fetching server state
// For most queries, it's usually sufficient to check for the isLoading state, then the isError state, then finally, assume that the data is available and render the successful state:
function Todos() {
const { isLoading, isError, data, error } = useQuery("todos", fetchTodoList);
if (isLoading) {
return <span>Loading...</span>;
}
if (isError) {
return <span>Error: {error.message}</span>;
}
// We can assume by this point that `isSuccess === true`
return (
<ul>
{data.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
);
}
const [data, setData] = useState(undefined);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(undefined);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(
"https://pokeapi.co/api/v2/pokemon?limit=100"
);
const data = await response.json();
setData(data.results);
} catch (e) {
setError(e.message || "Something went wrong");
}
// finally, don't care success or not
setIsLoading(false);
};
fetchData();
}, []);
if (error) {
return <Alert>Error {error}!! Please try again!!</Alert>;
}
if (isLoading) {
return <p>Loading...</p> || <Skeleton />;
}
const { results } = data;
return <ResultUI data={results} />;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment