Last active
February 28, 2022 04:11
-
-
Save mhaecal/db65b0abf4b4e8e6453e9a647b698f4b to your computer and use it in GitHub Desktop.
React Query with Pagination Example
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
import React from 'react' | |
import Character from './components/Character' | |
import { QueryClientProvider, QueryClient } from 'react-query' | |
const queryClient = new QueryClient() | |
function App() { | |
return ( | |
<div className="App"> | |
<QueryClientProvider client={queryClient}> | |
<Character /> | |
</QueryClientProvider> | |
</div> | |
) | |
} | |
export default App |
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
import React, { useState } from 'react' | |
import { useQuery } from 'react-query' | |
import { CharacterService } from '../services/CharacterService' | |
export default function Character() { | |
const [page, setPage] = useState(1) | |
const useCharacters = CharacterService.useCharacters(page) | |
const { data, isLoading, isError, isPreviousData, isFetching } = useCharacters | |
if (isLoading) return <div>Loading...</div> | |
if (isError) return <div>Error</div> | |
return ( | |
<div> | |
<h3>List character from rickandmortyapi.com</h3> | |
{data.results.map((character) => ( | |
<div key={character.id}> | |
{character.id}. {character.name} | |
</div> | |
))} | |
<button | |
disabled={isPreviousData || page === 1} | |
onClick={() => setPage((page) => page - 1)} | |
> | |
Previous | |
</button> | |
{/* isPreviousData => Disable the Next button until new data is available */} | |
<button | |
disabled={isPreviousData || !data.info.next} | |
onClick={() => setPage((page) => page + 1)} | |
> | |
Next | |
</button> | |
{isFetching ? <span>Loading...</span> : null} | |
</div> | |
) | |
} |
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
import { useQuery } from 'react-query' | |
export const CharacterService = { | |
useCharacters: (page) => { | |
const fetchCharacters = async () => { | |
const res = await fetch( | |
`https://rickandmortyapi.com/api/character?page=${page}` | |
) | |
return res.json() | |
} | |
return useQuery(['characters', page], fetchCharacters, { | |
keepPreviousData: true, | |
}) | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment