From 0bf38da923abc1b2e098f60cff9ca1f38d5d1c45 Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Wed, 24 Jun 2020 16:41:48 -0600 Subject: [PATCH] chore: revort index in basic example --- examples/basic/src/index.js | 139 +++++++++++++++++++++++++++--------- 1 file changed, 104 insertions(+), 35 deletions(-) diff --git a/examples/basic/src/index.js b/examples/basic/src/index.js index 29333b5aa9..cac385f825 100644 --- a/examples/basic/src/index.js +++ b/examples/basic/src/index.js @@ -3,48 +3,117 @@ import React from "react"; import ReactDOM from "react-dom"; import axios from "axios"; import { useQuery, queryCache } from "react-query"; -import { ReactQueryDevtools } from "react-query-devtools"; - -function useGetSomethingExample(id) { - return useQuery( - "todos", - async function queryFn() { - const { data } = await axios.get( - "https://jsonplaceholder.typicode.com/todos/" - ); - return data; - }, - { - onSuccess: async (data) => { - console.log(id, data[id]); - }, - } + +function App() { + const [postId, setPostId] = React.useState(-1); + + return ( + <> +

+ As you visit the posts below, you will notice them in a loading state + the first time you load them. However, after you return to this list and + click on any posts you have already visited again, you will see them + load instantly and background refresh right before your eyes!{" "} + + (You may need to throttle your network speed to simulate longer + loading sequences) + +

+ {postId > -1 ? ( + + ) : ( + + )} + ); } -function ExampleOne() { - useGetSomethingExample(1); - return
one
; -} +function Posts({ setPostId }) { + const { status, data, error, isFetching } = useQuery("posts", async () => { + const { data } = await axios.get( + "https://jsonplaceholder.typicode.com/posts" + ); + return data; + }); -function ExampleTwo() { - useGetSomethingExample(2); - return
two
; + return ( +
+

Posts

+
+ {status === "loading" ? ( + "Loading..." + ) : status === "error" ? ( + Error: {error.message} + ) : ( + <> + +
{isFetching ? "Background Updating..." : " "}
+ + )} +
+
+ ); } -export default function App() { +// This function is not inline to show how query keys are passed to the query function +// Normally, you can inline them if you want. +const getPostById = async (key, id) => { + const { data } = await axios.get( + `https://jsonplaceholder.typicode.com/posts/${id}` + ); + return data; +}; + +function Post({ postId, setPostId }) { + const { status, data, error, isFetching } = useQuery( + ["post", postId], + getPostById, + { + enabled: postId, + } + ); + return ( -
- - - - +
+ + {!postId || status === "loading" ? ( + "Loading..." + ) : status === "error" ? ( + Error: {error.message} + ) : ( + <> +

{data.title}

+
+

{data.body}

+
+
{isFetching ? "Background Updating..." : " "}
+ + )}
); }