Developing offline with TanStack Query (or React Query and tRPC)

So I discovered this one on a long flight with no internet access.

What if you want to code while not connected to the internet?

React Query does many clever things to make data fetching optimal, and one hidden benefit was auto-failing requests made while offline.

While usually a gem, I wanted a different behavior while coding offline.

The fix was altering the default network mode while developing offline.

Network Mode: always

While in always mode, TanStack Query will always fetch and ignore the online/offline state. networkMode: "always".

Full docs here

Examples

In case you haven't changed your options before here's a couple of examples with React Query and tRPC.

React Query

function usePosts() {
  return useQuery("posts", async () => {
    const { data } = await axios.get(
      "https://jsonplaceholder.typicode.com/posts"
    );
    return data;
  }, 
  // options configuration
  { networkMode: "offlineFirst" });
}

function Posts({ setPostId }) {
  const queryClient = useQueryClient();
  const { status, data, error, isFetching } = usePosts();

// ... rest of the code

tRPC

const { data, status } = trpc.comment.get.useQuery(
    { 
      postId,
    },
     // options configuration
    { networkMode: "always" }
  );
ReactjsReact QueryHelpTrpc
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.