Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Você usa APIs do jeito errado

Hugo
July 16, 2022

Você usa APIs do jeito errado

Uma introdução ao React Query v3

Hugo

July 16, 2022
Tweet

More Decks by Hugo

Other Decks in Programming

Transcript

  1. É 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(); }, [])
  2. É 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(); }, [])
  3. É 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(); }, [])
  4. É 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(); }, [])
  5. É 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(); }, [])
  6. 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(); }, [])
  7. function TimelinePage() { const timelineData = useTimelineData(); if (!timelineData) {

    return null; } return ( <Timeline> {timelineData.posts.map((post) => ( <Post key={post.id} post={post} /> ))} </Timeline> ) }
  8. 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; }
  9. 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; }
  10. Tá pronto Tá pronto? Alguém consegue me dizer quais são

    os problemas da implementação atual?
  11. Busca T Ty Type TypeSc TypeScri TypeScript Requisições T Ty

    Type TypeSc TypeScri TypeScript T T T T T T Race Condition
  12. T Ty Type TypeSc TypeScri TypeScript Requisições T Ty Type

    TypeSc TypeScri TypeScript Race Condition Latência T Ty Type TypeSc TypeScri TypeScript
  13. 1 4 3 2 Requisições 1 4 3 2 3

    Retry Retry Retry Sucesso Retries Retries
  14. Erros e Exceções Batching Caching Cache Invalidation Race Condition Retries

    Cancelamento Prefetching In fi nite Pagination Polling Optimistic Updates Refetching E muito mais
  15. 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; }
  16. function PostPage({params: {id}}) { const {data, isLoading} = usePostData(id); if

    (isLoading) { return null; } return ( <Post post={data.post} /> ) }
  17. function PostPage({params: {id}}) { const {data, isLoading} = usePostData(id); if

    (isLoading) { return null; } return ( <Post post={data.post} /> ) }
  18. function PostPage({params: {id}}) { const {data, isLoading} = usePostData(id); if

    (isLoading) { return null; } return ( <Post post={data.post} /> ) }
  19. Erros e Exceções Batching Caching Cache Invalidation Race Condition Retries

    Cancelamento Prefetching In fi nite Pagination Polling Optimistic Updates Refetching Sites Robustos
  20. function usePostData(id) { return useQuery(['posts', id], () => fetchPost(id), {

    staleTime: 1000 * 20, cacheTime: 1000, refetchOnWindowsFocus: false, }); }
  21. New

  22. 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(); }
  23. 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> ) }
  24. 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> ) }
  25. 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> ) }
  26. 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> )
  27. Hugo, eu parei de prestar atenção Já uso o getServerProps

    Não preciso do React Query E se eu te falar que...
  28. E se eu te falar que... React Query trabalha com

    dados assíncronos Qualquer dado assíncrono
  29. const [stream, setStream] = useState(); useEffect(() => { async function

    getMedia() { const newStream = await navigator.mediaDevices.getUserMedia({video: true}); setStream(newStream); } getMedia(); }, [])