Last active
November 23, 2022 14:01
-
-
Save json9512/8bc447d0c7206ca73daca5da79531e59 to your computer and use it in GitHub Desktop.
useQuery vs useQuery + useMutation + useEffect
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 { QueryClient, QueryClientProvider, useMutation, useQuery } from "@tanstack/react-query"; | |
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'; | |
import { debounce } from "lodash"; | |
import { useCallback, useEffect, useState } from "react"; | |
import './App.css'; | |
const queryClient = new QueryClient(); | |
// EX 1 - useQuery만 사용 | |
const fetchData = async (offset = 0) => { | |
const res = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=20&offset=${offset}`); | |
return res.json(); | |
} | |
const Main = () => { | |
const [offset, setOffset] = useState(); | |
const {data} = useQuery(['pokemons', offset], () => fetchData(offset)); | |
const onChange = useCallback((e) => { | |
debounce(() => { | |
setOffset(e.target.value) | |
}, 500)() | |
}, []) | |
return <div className="App" style={{display: "flex-col", justifyContent: "space-evenly"}}> | |
<h1>React Query</h1> | |
<input | |
onChange={onChange} | |
placeholder="set offset" /> | |
{data?.results && data.results.map((item) => <div key={item.name} style={{marginTop: 1+"vh"}}>{item.name}</div>)} | |
</div> | |
} | |
// EX 2 - useQuery + useMutation + useEffect | |
const Main2 = () => { | |
const [offset, setOffset] = useState(); | |
const {data} = useQuery(['pokemons', offset], () => fetchData(offset)); | |
const {mutate} = useMutation(fetchData, {onSuccess: () => queryClient.invalidateQueries(['pokemons', offset])}); // 차라리 queryClient.setQueryData를 쓰면? | |
useEffect(() => { | |
mutate(offset) | |
}, [offset, mutate]) | |
const onChange = useCallback((e) => { | |
debounce(() => { | |
setOffset(e.target.value) | |
}, 500)() | |
}, []) | |
return <div className="App" style={{display: "flex-col", justifyContent: "space-evenly"}}> | |
<h1>React Query</h1> | |
<input | |
onChange={onChange} | |
placeholder="set offset" /> | |
{data?.results && data.results.map((item) => <div key={item.name} style={{marginTop: 1+"vh"}}>{item.name}</div>)} | |
</div> | |
} | |
function App() { | |
return ( | |
<QueryClientProvider client={queryClient}> | |
<Main2 /> | |
<ReactQueryDevtools /> | |
</QueryClientProvider> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment