Queries
At Tia we use the query approach to data loading. That means we let a library – React Query – deal with fiddly details so we can focus on our stuff.
Nobody wants to waste time solving solved problems 😉
Why queries
React Query is modeled after the Apollo Client from GraphQL. For any type of data fetching.
You give it a function that loads data (from REST in our case) and React Query handles:
- loading & error states
- caching
- global request deduping
- helpful dev tools
- reloading stale data
- retrying until success
You give each query a name and the library uses it as a cache key.
Names can contain variable data, which makes queries reusable. Similar to how russian doll caching works in rails 👉 change the cache key to invalidate. Invalidating data is too hard.
Exercise
Load your doggos from the API – https://dog.ceo/dog-api/documentation/breed
Write a query with useQuery.
Wrap your app in a QueryClientProvider:
// outside the Appconst queryClient = new QueryClient()// inside the App<QueryClientProvider client={queryClient}>{/* rest of your app */}</QueryClientProvider>
You'll have to render everything inside the provider. I suggest creating a <Doggos /> component if you haven't yet.
const { data } = useQuery("doggos", async () => fetch)
Render a <Spinner> while your data is loading. You can pass fake doggos as a third argument to userQuery with { initialData } to avoid the spinner-of-doom-on-load problem.
Solution
You can find my solution at https://github.com/AskTia/tia-react-train/tree/solution-queries