Skip to content

Commit 4914918

Browse files
committed
reusable react query hook
1 parent 3e38459 commit 4914918

File tree

2 files changed

+26
-16
lines changed

2 files changed

+26
-16
lines changed

src/lib/hooks/useSuperHeroesData.tsx

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { useQuery } from 'react-query'
2+
import axios from 'axios'
3+
import { SuperHero } from 'interfaces'
4+
5+
interface Props {
6+
onSuccess: (response: any) => void
7+
onError: (error: Error) => void
8+
}
9+
10+
const fetchSuperHeroes = () => {
11+
return axios.get('http://localhost:4000/superheroes')
12+
}
13+
14+
export const useSuperHeroesData = ({ onSuccess, onError }: Props) => {
15+
return useQuery('super-heroes', fetchSuperHeroes, {
16+
onError,
17+
onSuccess,
18+
select: (response) => {
19+
const result = response.data.map((hero: SuperHero) => hero.name)
20+
return result
21+
},
22+
})
23+
}

src/pages/RQSuperHeroes/RQSuperHeroes.tsx

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,8 @@
1-
import { FC, useState } from 'react'
2-
import { useQuery } from 'react-query'
3-
import axios from 'axios'
4-
import { SuperHero } from 'interfaces'
1+
import { FC } from 'react'
2+
import { useSuperHeroesData } from 'lib/hooks/useSuperHeroesData'
53

64
interface Props {}
75

8-
const fetchSuperHeroes = () => {
9-
return axios.get('http://localhost:4000/superheroes')
10-
}
11-
126
const RQSuperHeroes: FC<Props> = (props: Props) => {
137
const onError = (error: Error) => {
148
console.log('Perform side effect after encountering error', error)
@@ -18,14 +12,7 @@ const RQSuperHeroes: FC<Props> = (props: Props) => {
1812
console.log('Perform side effect after encountering error', response)
1913
}
2014

21-
const { data, isLoading, isError, error, isFetching } = useQuery('super-heroes', fetchSuperHeroes, {
22-
onError,
23-
onSuccess,
24-
select: (response) => {
25-
const result = response.data.map((hero: SuperHero) => hero.name)
26-
return result
27-
},
28-
})
15+
const { data, isLoading, isError, error, isFetching } = useSuperHeroesData({ onSuccess, onError })
2916

3017
console.log({ isLoading, isFetching })
3118

0 commit comments

Comments
 (0)