Gathering detailed insights and metrics for @lukesmurray/react-query-autosync
Gathering detailed insights and metrics for @lukesmurray/react-query-autosync
Gathering detailed insights and metrics for @lukesmurray/react-query-autosync
Gathering detailed insights and metrics for @lukesmurray/react-query-autosync
npm install @lukesmurray/react-query-autosync
Typescript
Module System
Node Version
NPM Version
Total Downloads
798
Last Day
1
Last Week
5
Last Month
14
Last Year
130
Minified
Minified + Gzipped
Latest Version
0.0.3
Package Id
@lukesmurray/react-query-autosync@0.0.3
Unpacked Size
134.98 kB
Size
28.51 kB
File Count
26
NPM Version
8.19.2
Node Version
16.18.0
Cumulative downloads
Total Downloads
Last Day
0%
1
Compared to previous day
Last Week
25%
5
Compared to previous week
Last Month
0%
14
Compared to previous month
Last Year
-1.5%
130
Compared to previous year
1
3
35
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.
1# npm 2npm install use-react-query-auto-sync 3 4# yarn 5yarn add use-react-query-auto-sync
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.
1function Example() {
2 const { draft, setDraft, queryResult } = useReactQueryAutoSync({
3 queryOptions: { /* omitted but same as react-query */ },
4 mutationOptions: { /* omitted but same as react-query */ },
5 autoSaveOptions: { wait: 1000 },
6 });
7
8 const loading = queryResult.isLoading;
9
10 if (loading) {
11 return <div>Loading...</div>;
12 } else {
13 return (
14 <div>
15 <input type="text" value={draft} onChange={(e) => setDraft(e.target.value)}></input>
16 </div>
17 );
18 }
19}
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
ParametersqueryOptions
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
ParametersSame as useReactQueryAutoSync
but does not have queryOptions
.
autoSaveOptions
wait
: number of milliseconds to delay the debounce functionmaxWait
: 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.
1const exampleAtom = atom(undefined);
2
3function Example() {
4 const [draft_, setDraft_] = useAtom(exampleAtom);
5 const { draft, setDraft, queryResult } = useReactQueryAutoSync({
6 queryOptions: { /* omitted */ },
7 mutationOptions: { /* omitted */ },
8 autoSaveOptions: { wait: 1000 },
9 draftProvider: { draft: draft_, setDraft: setDraft_ },
10 });
⚠️ 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.
Here is a more complex example which shows off more of the features of useReactQueryAutoSync
.
1import React from "react";
2import { useReactQueryAutoSync } from "../lib/useReactQueryAutoSync";
3
4// fake api object. You would supply your own!
5const fakeAPI: any = {};
6
7// fake function used to merge server and local state
8const mergeFoo: any = (remote: any, local: any) => ({ ...remote, ...local });
9
10export function Demo() {
11 const { draft, setDraft } = useReactQueryAutoSync({
12 queryOptions: {
13 queryKey: "foo",
14 queryFn: async () => fakeAPI.fetchFoo(),
15 // if you want to poll the server pass a refetchInterval to react query
16 refetchInterval: 5000,
17 },
18 mutationOptions: {
19 mutationFn: async (foo) => fakeAPI.saveFoo(foo),
20 },
21 // pass autoSaveOptions to automatically save to the server with debouncing
22 autoSaveOptions: {
23 wait: 500,
24 },
25 // pass alertIfUnsavedChanges to notify user if they leave with unsaved changes
26 alertIfUnsavedChanges: true,
27 // pass merge to merge server and local state when the server state updates
28 merge: (remoteFoo, localFoo) => mergeFoo(remoteFoo, localFoo),
29 });
30
31 return (
32 <>
33 <input
34 type="text"
35 value={draft.foo}
36 onChange={(e) => {
37 // modify draft with `setDraft` but make sure to modify a copy so you
38 // don't break the ReactQuery caching!
39 setDraft({ ...draft, foo: e.target.value });
40 }}
41 />
42 </>
43 );
44}
yarn build && npm publish --access public
No vulnerabilities found.
No security vulnerabilities found.