npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-react-query-auto-sync

v0.1.0

Published

![](https://img.shields.io/npm/v/use-react-query-auto-sync?label=npm) ![](https://img.shields.io/bundlephobia/minzip/use-react-query-auto-sync)

Downloads

1,427

Readme

useReactQueryAutoSync

A helpful react hook for building interfaces which require autosave. Read more about the motivation and design in the original blog post. Check out the quick example below or feel free to view the drawing demo online. The code for the demo is in the src folder and can be run locally with yarn dev. The hook is used in the useStrokes function in src/components/Demo.tsx.

Installation

# npm
npm install use-react-query-auto-sync

# yarn
yarn add use-react-query-auto-sync

Documentation

The library exposes two hooks useReactQueryAutoSync and useReactQueryAutoSave. Both hooks return an object which contains draft and setDraft properties which can be treated similarly to the state and setState values returned by useState. The key thing this library does is provide mechanisms to automatically save and load changes to the draft value between the server and the client, all through a simple API. Both hooks directly expose react query options so they are simple to configure and use. This is easiest to see with an example.

function Example() {
  const { draft, setDraft, queryResult } = useReactQueryAutoSync({
    queryOptions: { /* omitted but same as react-query */ },
    mutationOptions: { /* omitted but same as react-query */ },
    autoSaveOptions: { wait: 1000 },
  });

  const loading = queryResult.isLoading;

  if (loading) {
    return <div>Loading...</div>;
  } else {
    return (
      <div>
        <input type="text" value={draft} onChange={(e) => setDraft(e.target.value)}></input>
      </div>
    );
  }
}

In this example we use query and mutation options to tell useReactQueryAutoSync how to fetch and save the value to the server. We use the autoSaveOptions parameter to tell useReactQueryAutoSync to debounce changes and automatically synchronize the value to the server after one second without any changes.

Similarly to useState you can only change the draft value using the setDraft function.

In addition to the sync hook the library exposes useReactQueryAutoSave (save). The difference between the two is the save hook is unidirectional and only saves a local value to the server when the local value changes. This can be useful for automatically saving things like logs, user analytics, or error reports. The sync hook is useful for things like documents where you don't want the user to have to press a save button to keep their changes.

useReactQueryAutoSync Parameters

  • queryOptions required: these are the query options passed to useQuery. Make sure to set refetchInterval if you want to enable automatic polling. React query auto sync does not support query data selectors so make sure not to pass select. This is because react query auto sync expects the input to the mutate function to have the same type as the return value of the query function.
  • mutationOptions required: these are the mutation options passed to useMutation. Internally the hook uses onMutate, onError, and onSettled to optimistically update the state but it will call your versions of these functions as well. The hook uses the key previousData to save the previous data in the onMutate context.
  • autoSaveOptions: see autoSaveOptionsBelow. If undefined the hook will not automatically save data since it will assume a debounce time of Infinity.
  • merge: function used to merge updates from the server with local changes to server data. If undefined the hook will ignore background updates from the server even if refetchInterval is supplied and local changes will take precedence. The merge function is also used when an error occurs while saving data.
  • alertIfUnsavedChanges: ask the user to confirm before leaving the page if there are unsaved changes. If undefined the hook will not ask the user to confirm before leaving.
  • mutateEnabled: similar to the enabled parameter of useQuery. If mutateEnabled is false and the hook tries to save to the server, a pending save will be created, and when mutateEnabled is toggled to true the pending save will immediately execute. Can be useful if you need to use dependent queries to get data to perform the mutation. If undefined, mutateEnabled defaults to true.
  • draftProvider: experimental see draftProviderBelow. If undefined the hook will use useState to create the draft value.

useReactQueryAutoSave Parameters

Same as useReactQueryAutoSync but does not have queryOptions.

autoSaveOptions

  • wait: number of milliseconds to delay the debounce function
  • maxWait: maximum number of milliseconds to delay the debounce function. If undefined there is no max delay.

draftProvider (experimental)

  • draft: The current value of the draft.
  • setDraft: Function used to update the draft. (value) => void.

By default useReactQueryAutoSync uses useState to implement the draft. However there are times when this is not desired. For example, if you want to display the same synchronized value in multiple places in your application you have to either lift state up or use a react context. If you try using useReactQueryAutoSync in multiple locations the values may eventually sync but it would be a sub optimal experience since synchronizing the values would require multiple round trips to the server. Instead you can use the draftProvider and provide your own draft values backed by a library such as recoil or jotai or zustand. Here is a simple example which creates a draftProvider using jotai. Regardless of where you use this hook the draft values will be immediately synchronized.

const exampleAtom = atom(undefined);

function Example() {
  const [draft_, setDraft_] = useAtom(exampleAtom);
  const { draft, setDraft, queryResult } = useReactQueryAutoSync({
    queryOptions: { /* omitted */ },
    mutationOptions: { /* omitted */ },
    autoSaveOptions: { wait: 1000 },
    draftProvider: { draft: draft_, setDraft: setDraft_ },
  });

⚠️ This is an experimental feature and has issues such as potentially issuing a mutation for each hook.

For instructions on how to use draftProvider safely check this issue comment.

Example

Here is a more complex example which shows off more of the features of useReactQueryAutoSync.

import React from "react";
import { useReactQueryAutoSync } from "../lib/useReactQueryAutoSync";

// fake api object. You would supply your own!
const fakeAPI: any = {};

// fake function used to merge server and local state
const mergeFoo: any = (remote: any, local: any) => ({ ...remote, ...local });

export function Demo() {
  const { draft, setDraft } = useReactQueryAutoSync({
    queryOptions: {
      queryKey: "foo",
      queryFn: async () => fakeAPI.fetchFoo(),
      // if you want to poll the server pass a refetchInterval to react query
      refetchInterval: 5000,
    },
    mutationOptions: {
      mutationFn: async (foo) => fakeAPI.saveFoo(foo),
    },
    // pass autoSaveOptions to automatically save to the server with debouncing
    autoSaveOptions: {
      wait: 500,
    },
    // pass alertIfUnsavedChanges to notify user if they leave with unsaved changes
    alertIfUnsavedChanges: true,
    // pass merge to merge server and local state when the server state updates
    merge: (remoteFoo, localFoo) => mergeFoo(remoteFoo, localFoo),
  });

  return (
    <>
      <input
        type="text"
        value={draft.foo}
        onChange={(e) => {
          // modify draft with `setDraft` but make sure to modify a copy so you
          // don't break the ReactQuery caching!
          setDraft({ ...draft, foo: e.target.value });
        }}
      />
    </>
  );
}