Last active
May 3, 2022 17:05
-
-
Save nguyenit67/631d65baff7e7ce172666331c6c33d21 to your computer and use it in GitHub Desktop.
manual hooks for fetching server state
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
// 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> | |
); | |
} |
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
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