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
バイブコーディングの正体——AIエージェントはソフトウェア開発を変えるか?
stakaya
5
920
Terraform やるなら公式スタイルガイドを読もう 〜重要項目 10選〜
hiyanger
13
3.1k
自作OSでDOOMを動かしてみた
zakki0925224
1
1.3k
画像コンペでのベースラインモデルの育て方
tattaka
3
1.7k
「リーダーは意思決定する人」って本当?~ 学びを現場で活かす、リーダー4ヶ月目の試行錯誤 ~
marina1017
0
220
ゲームの物理
fadis
5
1.1k
DataformでPythonする / dataform-de-python
snhryt
0
170
技術的負債で信頼性が限界だったWordPress運用をShifterで完全復活させた話
rvirus0817
1
1.7k
未来を拓くAI技術〜エージェント開発とAI駆動開発〜
leveragestech
2
130
オホーツクでコミュニティを立ち上げた理由―地方出身プログラマの挑戦 / TechRAMEN 2025 Conference
lemonade_37
2
470
AIに安心して任せるためにTypeScriptで一意な型を作ろう
arfes0e2b3c
0
360
AIのメモリー
watany
13
1.4k
Featured
See All Featured
Designing for Performance
lara
610
69k
StorybookのUI Testing Handbookを読んだ
zakiyama
30
6k
Designing Dashboards & Data Visualisations in Web Apps
destraynor
231
53k
Fireside Chat
paigeccino
39
3.6k
Reflections from 52 weeks, 52 projects
jeffersonlam
351
21k
Rails Girls Zürich Keynote
gr2m
95
14k
How To Stay Up To Date on Web Technology
chriscoyier
790
250k
Automating Front-end Workflow
addyosmani
1370
200k
The Invisible Side of Design
smashingmag
301
51k
GraphQLとの向き合い方2022年版
quramy
49
14k
GraphQLの誤解/rethinking-graphql
sonatard
71
11k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
367
26k
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