Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Você usa APIs do jeito errado
Search
Hugo
July 16, 2022
Programming
0
66
Você usa APIs do jeito errado
Uma introdução ao React Query v3
Hugo
July 16, 2022
Tweet
Share
More Decks by Hugo
See All by Hugo
ReferenceError: talk is not defined
hugooliveirad
1
47
Três hábitos para escrever CSS escalável
hugooliveirad
0
630
Three habits to write scalable CSS
hugooliveirad
0
65
Mantendo webapps em produção, sem dor de cabeça
hugooliveirad
1
280
Minha webapp está em produção, e agora?
hugooliveirad
0
38
Other Decks in Programming
See All in Programming
複雑なドメインに挑む.pdf
yukisakai1225
5
1.1k
Performance for Conversion! 分散トレーシングでボトルネックを 特定せよ
inetand
0
130
Compose Multiplatform × AI で作る、次世代アプリ開発支援ツールの設計と実装
thagikura
0
140
アセットのコンパイルについて
ojun9
0
120
Swift Updates - Learn Languages 2025
koher
2
470
個人軟體時代
ethanhuang13
0
320
Cache Me If You Can
ryunen344
2
680
そのAPI、誰のため? Androidライブラリ設計における利用者目線の実践テクニック
mkeeda
2
270
さようなら Date。 ようこそTemporal! 3年間先行利用して得られた知見の共有
8beeeaaat
3
1.4k
意外と簡単!?フロントエンドでパスキー認証を実現する WebAuthn
teamlab
PRO
2
730
Android 16 × Jetpack Composeで縦書きテキストエディタを作ろう / Vertical Text Editor with Compose on Android 16
cc4966
1
190
HTMLの品質ってなんだっけ? “HTMLクライテリア”の設計と実践
unachang113
4
2.8k
Featured
See All Featured
Building Adaptive Systems
keathley
43
2.7k
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
234
17k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
656
61k
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
53
2.9k
Embracing the Ebb and Flow
colly
87
4.8k
XXLCSS - How to scale CSS and keep your sanity
sugarenia
248
1.3M
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
29
2.9k
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
PRO
188
55k
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
31
2.5k
Agile that works and the tools we love
rasmusluckow
330
21k
Music & Morning Musume
bryan
46
6.8k
Rebuilding a faster, lazier Slack
samanthasiow
83
9.2k
Transcript
Você usa APIs do jeito errado Uma introdução ao React
Query
Oi, eu sou o Hugo E eu também já usei
APIs do jeito errado
Vamos começar um projeto novo
None
None
A API da timeline está pronta
A API da timeline está pronta Beleza, a gente vai
implementar
É só substituir os valores do JSON pela API const
[timelineData, setTimelineData] = useState(); useEffect(() => { async function fetchData() { const response = await fetch('/timeline'); const data = await response.json(); setTimelineData(data); } fetchData(); }, [])
É só substituir os valores do JSON pela API const
[timelineData, setTimelineData] = useState(); useEffect(() => { async function fetchData() { const response = await fetch('/timeline'); const data = await response.json(); setTimelineData(data); } fetchData(); }, [])
É só substituir os valores do JSON pela API const
[timelineData, setTimelineData] = useState(); useEffect(() => { async function fetchData() { const response = await fetch('/timeline'); const data = await response.json(); setTimelineData(data); } fetchData(); }, [])
É só substituir os valores do JSON pela API const
[timelineData, setTimelineData] = useState(); useEffect(() => { async function fetchData() { const response = await fetch('/timeline'); const data = await response.json(); setTimelineData(data); } fetchData(); }, [])
É só substituir os valores do JSON pela API const
[timelineData, setTimelineData] = useState(); useEffect(() => { async function fetchData() { const response = await fetch('/timeline'); const data = await response.json(); setTimelineData(data); } fetchData(); }, [])
function useTimelineData() { } É só substituir os valores do
JSON pela API const [timelineData, setTimelineData] = useState(); useEffect(() => { async function fetchData() { const response = await fetch('/timeline'); const data = await response.json(); setTimelineData(data); } fetchData(); }, [])
function TimelinePage() { const timelineData = useTimelineData(); if (!timelineData) {
return null; } return ( <Timeline> {timelineData.posts.map((post) => ( <Post key={post.id} post={post} /> ))} </Timeline> ) }
Tá pronto, chefe
Tá pronto, chefe Agora a API dos posts está pronta
Tá pronto, chefe Agora a API dos posts está pronta
Beleza, vamos lá. Tá fácil.
None
function usePostData(id) { const [postData, setPostData] = useState(); useEffect(() =>
{ async function fetchData() { const response = await fetch(`/posts/${id}`); const data = await response.json(); setPostData(data); } fetchData(); }, [id]) return postData; }
function usePostData(id) { const [postData, setPostData] = useState(); useEffect(() =>
{ async function fetchData() { const response = await fetch(`/posts/${id}`); const data = await response.json(); setPostData(data); } fetchData(); }, [id]) return postData; }
Tá pronto
Tá pronto Tá pronto?
Tá pronto Tá pronto? Alguém consegue me dizer quais são
os problemas da implementação atual?
Alguém consegue me dizer quais são os problemas da implementação
atual?
Erros e Exceções
Erros e Exceções
Error Erros e Exceções
Batching
1 4 3 2 useTimelineData Batching
1 4 3 2 useTimelineData Batching Batching
1 4 3 2 useTimelineData Batching Batching
Caching
Caching
Caching useTimelineData
Cache Invalidation New
Cache Invalidation New New
Race Condition
Race Condition Busca T T T T T T
Busca T Ty Type TypeSc TypeScri TypeScript T T T
T T T Race Condition
Busca T Ty Type TypeSc TypeScri TypeScript Requisições T Ty
Type TypeSc TypeScri TypeScript T T T T T T Race Condition
T Ty Type TypeSc TypeScri TypeScript Requisições T Ty Type
TypeSc TypeScri TypeScript Race Condition Latência T Ty Type TypeSc TypeScri TypeScript
Retries
Retries
1 4 3 2 Requisições Retries
1 4 3 2 Requisições 1 4 3 2 Retries
1 4 3 2 Requisições 1 4 3 2 3
Retry Retry Retry Sucesso Retries Retries
Erros e Exceções Batching Caching Cache Invalidation Race Condition Retries
Erros e Exceções Batching Caching Cache Invalidation Race Condition Retries
Cancelamento Prefetching In fi nite Pagination Polling Optimistic Updates Refetching E muito mais
Ninguém implementa tudo isso
Você não quer ter que implementar tudo isso
React Query
function usePostData(id) { const [postData, setPostData] = useState(); useEffect(() =>
{ async function fetchData() { const response = await fetch(`/posts/${id}`); const data = await response.json(); setPostData(data); } fetchData(); }, [id]) return postData; }
async function fetchData() { const response = await fetch(`/posts/${id}`); const
data = await response.json(); setPostData(data); }
async function fetchData() { const response = await fetch(`/posts/${id}`); const
data = await response.json(); setPostData(data); }
async function fetchData() { const response = await fetch(`/posts/${id}`); return
response.json(); setPostData(data); }
function usePostData(id) { return useQuery(['posts', id], () => fetchPost(id)); }
function usePostData(id) { return useQuery(['posts', id], () => fetchPost(id)); }
function usePostData(id) { return useQuery(['posts', id], () => fetchPost(id)); }
function usePostData(id) { return useQuery(['posts', id], () => fetchPost(id)); }
function PostPage({params: {id}}) { const {data, isLoading} = usePostData(id); if
(isLoading) { return null; } return ( <Post post={data.post} /> ) }
function PostPage({params: {id}}) { const {data, isLoading} = usePostData(id); if
(isLoading) { return null; } return ( <Post post={data.post} /> ) }
function PostPage({params: {id}}) { const {data, isLoading} = usePostData(id); if
(isLoading) { return null; } return ( <Post post={data.post} /> ) }
const { data, isLoading, isSuccess, error, isError, refetch, /* ...
*/ } = usePostData(id);
Erros e Exceções Batching Caching Cache Invalidation Race Condition Retries
Cancelamento Prefetching In fi nite Pagination Polling Optimistic Updates Refetching Sites Robustos
Con fi gurável
staleTime: 0
staleTime: 0 ... 0 ms
cacheTime: 1000 * 60 * 5
retry: 3
refetchOnWindowFocus: true
refetchOnWindowFocus: true ... ...
function usePostData(id) { return useQuery(['posts', id], () => fetchPost(id), {
staleTime: 1000 * 20, cacheTime: 1000, refetchOnWindowsFocus: false, }); }
Mutations
New
New New u
New New useMutation
async function createPost(post) { const response = await fetch('/posts', {
method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(post) }); return response.json(); }
function CreatePostPage() { const mutation = useMutation(createPost); const handleSubmit =
useCallback((event) => { event.preventDefault(); const data = new FormData(event.target); const post = Object.fromEntries(data.entries()); mutation.mutate(post); }, [mutation]); return mutation.isLoading ? (<Spinner />) : ( <form onSubmit={handleSubmit}> {/* ... */} </form> ) }
function CreatePostPage() { const mutation = useMutation(createPost); const handleSubmit =
useCallback((event) => { event.preventDefault(); const data = new FormData(event.target); const post = Object.fromEntries(data.entries()); mutation.mutate(post); }, [mutation]); return mutation.isLoading ? (<Spinner />) : ( <form onSubmit={handleSubmit}> {/* ... */} </form> ) }
function CreatePostPage() { const mutation = useMutation(createPost); const handleSubmit =
useCallback((event) => { event.preventDefault(); const data = new FormData(event.target); const post = Object.fromEntries(data.entries()); mutation.mutate(post); }, [mutation]); return mutation.isLoading ? (<Spinner />) : ( <form onSubmit={handleSubmit}> {/* ... */} </form> ) }
function CreatePostPage() { const mutation = useMutation(createPost); const queryClient =
useQueryClient(); const handleSubmit = useCallback((event) => { event.preventDefault(); const data = new FormData(event.target); const post = Object.fromEntries(data.entries()); mutation.mutate(post, { onSuccess: () => { queryClient.invalidateQueries('timeline'); } }); }, [mutation]); return mutation.isLoading ? (<Spinner />) : ( <form onSubmit={handleSubmit}> {/* ... */} </form> )
queryClient.invalidateQueries(['posts', id]);
DevTools
DevTools
Hugo, eu parei de prestar atenção Já uso o getServerProps
Não preciso do React Query
Hugo, eu parei de prestar atenção Já uso o getServerProps
Não preciso do React Query E se eu te falar que...
E se eu te falar que... React Query trabalha com
dados assíncronos
E se eu te falar que... React Query trabalha com
dados assíncronos Qualquer dado assíncrono
const [stream, setStream] = useState(); useEffect(() => { async function
getMedia() { const newStream = await navigator.mediaDevices.getUserMedia({video: true}); setStream(newStream); } getMedia(); }, [])
function useUserMedia() { return useQuery( ['userMedia'], () => navigator.mediaDevices.getUserMedia({video: true})
); }
function useUserMedia() { return useQuery( ['userMedia'], () => navigator.mediaDevices.getUserMedia({video: true}),
{ staleTime: Infinity } ); }
"The best part is no part"
None
De nada!
None
None
None