NEXT.JS 10 // REACT-QUERY // AXIOS // DATASTAX DOCUMENT API

6 Tricks for Next-Level CRUDs

Cache more, fetch less with React Query

Image for post
Image for post
npm install axios axios-auth-refresh react-query react-query-devtools sass

1. CACHE YOUR DATA WITH A REVALIDATION LIBRARY

React Query more than fit the bill: a low-carb request wrapper that follows the “stale-while-revalidate” approach to data fetching. Vercel’s similar SWR hook library also looked like a good option (Vercel being the creators of the Next.js framework) but React Query author Tanner Linsley’s polished docs and devtools made his library an almost irresistible choice.

Image for post
Image for post
Tanner’s Comparison Table is helpful. See also: Why You Should Use React Query or SWR

2. SET YOUR DEFAULTS WITH AXIOS

Different APIs are finicky about different headers. Any day I can DRY up my boilerplate with some global defaults is a great day.

Those are my variables, get yours at DataStax.

3. REFRESH TOKENS WITH AXIOS-AUTH-REFRESH

Authentication panic is common, what’s really refreshing is accepting help, as I did when I installed this calming token authenticator.

Axios-auth-refresh boilerplate, except for ‘X-Cassandra-Token’ and the pause config.
Image for post
Image for post
The token in local storage is just for debugging.

4. PRE-LOAD YOUR QUERY CACHE (WITHOUT PRE-FETCHING)

My favorite React Query trick: instead of requesting data for every detail view, React Query builds a cache from your first paginated GET.

Load up the cache from your app’s first GET

5. EXPORT SELF-DESCRIPTIVE HOOKS

All our CRUD operations are now simple and exportable. React-Query lets us specify our cache policy during and after each query or mutation.

react-query’s useQuery and useMutation hooks

6. SYNC EVERYTHING WITH YOUR HOOKS

Our Items index now runs with just two hooks, an items query hook and an addItem mutation hook. Each comes with a full menu of lifecycle booleans.

The items hook fetches the data and sets the cache. The addItem hook invalidates them.
The saveItem hook on each item’s dynamic route page uses Optimistic Updates.
Image for post
Image for post
Image for post
Image for post

Written by

ML Developer, comic book stacker

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store