Skip to content

Commit 2eb44ed

Browse files
committed
Initial query data
1 parent 78c3b07 commit 2eb44ed

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,10 @@ Sometimes a single component needs to call multiple APIs to fetch the necessary
9696

9797
Dependent query - is dependent on the results of another query.
9898

99+
**11. react-query initialData - Initial query data**
100+
101+
On react-query heroes page we have displayed different heroes. If we click on the hero, we see `loading` text for a moment. To get rid of that initial loading statement, we can set `initialData` in useSuperHeroData.tsx file. If we refresh detail page, the loading button will show because we don't have any initial data at the start, because we skipped the fetch all super heroes query.
102+
99103
## Available Scripts
100104

101105
In the project directory, you can run:

src/lib/hooks/useSuperHeroData.tsx

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useQuery } from 'react-query'
1+
import { useQuery, useQueryClient } from 'react-query'
22
import axios from 'axios'
33
import { SuperHero } from 'interfaces'
44

@@ -14,8 +14,20 @@ const fetchSuperHero = ({ queryKey }: { queryKey: any[] }) => {
1414
}
1515

1616
export const useSuperHeroData = ({ onSuccess, onError, heroId }: Props) => {
17+
const queryClient = useQueryClient()
1718
return useQuery(['super-hero', heroId], fetchSuperHero, {
1819
onError,
1920
onSuccess,
21+
initialData: () => {
22+
const hero = (queryClient.getQueryData('super-heroes') as any)?.data?.find(
23+
(hero: SuperHero) => hero.id === parseInt(heroId),
24+
)
25+
26+
if (hero) {
27+
return { data: hero }
28+
} else {
29+
return undefined
30+
}
31+
},
2032
})
2133
}

src/pages/RQSuperHero/RQSuperHero.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ const RQSuperHero: FC = () => {
1212
}
1313

1414
const { heroId } = useParams()
15-
const { data, isLoading, isError, error } = useSuperHeroData({ onSuccess, onError, heroId: heroId ?? '' })
15+
const { data, isLoading, isError, error } = useSuperHeroData({ onError, onSuccess, heroId: heroId ?? '' })
1616

1717
if (isLoading) {
1818
return <h2>Loading...</h2>

0 commit comments

Comments
 (0)