Skip to content

Commit

Permalink
Merge pull request #267 from psteinroe/fix/do-not-revalidate-on-mutate
Browse files Browse the repository at this point in the history
fix/do not revalidate on mutate
  • Loading branch information
psteinroe authored Aug 8, 2023
2 parents dd62bdb + 2f52243 commit bb2a667
Show file tree
Hide file tree
Showing 13 changed files with 71 additions and 20 deletions.
5 changes: 5 additions & 0 deletions .changeset/dull-coats-sniff.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@supabase-cache-helpers/postgrest-swr": patch
---

fix: do not revalidate on mutate by default
1 change: 1 addition & 0 deletions docs/pages/_meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"index": {
"title": "Introduction"
},
"configuration": "Configuration",
"postgrest": "PostgREST",
"storage": "Storage"
}
29 changes: 29 additions & 0 deletions docs/pages/configuration.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Callout, Tabs, Tab } from "nextra-theme-docs";
import Link from "next/link";

# Configuration

Supabase Cache Helpers does a decent job at keeping your data up-to-date. This allows you to deviate from the standard configuration and reduce the number of requests to your backend while keeping your app fresh.

<Tabs items={['SWR', 'React Query']}>
<Tab>
```tsx
function Page() {
return (
<SWRConfig
value={{
revalidateIfStale: false,
revalidateOnFocus: false,
>
...
</SWRConfig>
)
}
```
</Tab>
<Tab>
```tsx
// TODO
```
</Tab>
</Tabs>
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,7 @@ describe('useSubscription', () => {
client
.from('contact')
.select('id,username,ticket_number', { count: 'exact' })
.eq('username', USERNAME_1),
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
}
.eq('username', USERNAME_1)
);

const [cbCalled, setCbCalled] = useState<boolean>(false);
Expand All @@ -56,14 +52,14 @@ describe('useSubscription', () => {
filter: `username=eq.${USERNAME_1}`,
},
['id'],
{ callback: () => setCbCalled(true) }
{ callback: () => setCbCalled(true), revalidate: true }
);

const ticketNumber = Array.isArray(data) ? data[0]?.ticket_number : null;

return (
<div>
{(data ?? []).map((d) => (
<span key={d.id}>{`ticket_number: ${d.ticket_number}`}</span>
))}
<span key={ticketNumber}>{`ticket_number: ${ticketNumber}`}</span>
<span data-testid="count">{`count: ${count}`}</span>
<span data-testid="status">{status}</span>
<span data-testid="callback-called">{`cbCalled: ${cbCalled}`}</span>
Expand Down Expand Up @@ -93,9 +89,9 @@ describe('useSubscription', () => {
.eq('username', USERNAME_1)
.throwOnError();
});
await screen.findByText('ticket_number: 5', {}, { timeout: 10000 });
expect(screen.getByTestId('count').textContent).toEqual('count: 1');
await screen.findByText('cbCalled: true', {}, { timeout: 10000 });
await screen.findByText('ticket_number: 5', {}, { timeout: 20000 });
expect(screen.getByTestId('count').textContent).toEqual('count: 1');
unmount();
});
});
10 changes: 7 additions & 3 deletions packages/postgrest-swr/__tests__/utils.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
import { render } from '@testing-library/react';
import * as dotenv from 'dotenv';
import { resolve } from 'node:path';
import React from 'react';
import { SWRConfig } from 'swr';
import { resolve } from 'node:path';

import * as dotenv from 'dotenv';
dotenv.config({ path: resolve(__dirname, '../../../.env.local') });

export const renderWithConfig = (
element: React.ReactElement,
config: Parameters<typeof SWRConfig>[0]['value']
): ReturnType<typeof render> => {
const TestSWRConfig = ({ children }: { children: React.ReactNode }) => (
<SWRConfig value={config}>{children}</SWRConfig>
<SWRConfig
value={{ revalidateOnFocus: false, revalidateIfStale: false, ...config }}
>
{children}
</SWRConfig>
);
return render(element, { wrapper: TestSWRConfig });
};
8 changes: 5 additions & 3 deletions packages/postgrest-swr/src/cache/use-delete-item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
deleteItem,
DeleteItemProps,
} from '@supabase-cache-helpers/postgrest-mutate';
import { useSWRConfig } from 'swr';
import { MutatorOptions, useSWRConfig } from 'swr';

import { decode, usePostgrestFilterCache } from '../lib';
import { getMutableKeys } from '../lib/mutable-keys';
Expand All @@ -16,7 +16,7 @@ import { getMutableKeys } from '../lib/mutable-keys';
* @returns A function that takes a record of type `Type` and returns a promise that resolves once the record has been deleted from the cache.
* **/
export function useDeleteItem<Type extends Record<string, unknown>>(
opts: Omit<DeleteItemProps<Type>, 'input'>
opts: Omit<DeleteItemProps<Type>, 'input'> & MutatorOptions<Type>
): (input: Type) => Promise<void> {
const { mutate, cache } = useSWRConfig();
const getPostgrestFilter = usePostgrestFilterCache();
Expand All @@ -30,7 +30,9 @@ export function useDeleteItem<Type extends Record<string, unknown>>(
{
cacheKeys: getMutableKeys(Array.from(cache.keys())),
getPostgrestFilter,
mutate,
mutate: (key, data) => {
mutate(key, data, { ...opts, revalidate: opts?.revalidate ?? false });
},
decode,
}
);
Expand Down
11 changes: 8 additions & 3 deletions packages/postgrest-swr/src/cache/use-upsert-item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
upsertItem,
UpsertItemProps,
} from '@supabase-cache-helpers/postgrest-mutate';
import { useSWRConfig } from 'swr';
import { MutatorOptions, useSWRConfig } from 'swr';

import { decode, usePostgrestFilterCache } from '../lib';
import { getMutableKeys } from '../lib/mutable-keys';
Expand All @@ -16,7 +16,7 @@ import { getMutableKeys } from '../lib/mutable-keys';
* @returns A function that takes a record of type `Type` and returns a promise that resolves once the record has been upserted into the cache.
* **/
export function useUpsertItem<Type extends Record<string, unknown>>(
opts: Omit<UpsertItemProps<Type>, 'input'>
opts: Omit<UpsertItemProps<Type>, 'input'> & MutatorOptions<Type>
): (input: Type) => Promise<void> {
const { mutate, cache } = useSWRConfig();
const getPostgrestFilter = usePostgrestFilterCache();
Expand All @@ -30,7 +30,12 @@ export function useUpsertItem<Type extends Record<string, unknown>>(
{
cacheKeys: getMutableKeys(Array.from(cache.keys())),
getPostgrestFilter,
mutate,
mutate: (key, data) => {
mutate(key, data, {
...opts.opts,
revalidate: opts?.revalidate ?? false,
});
},
decode,
}
);
Expand Down
1 change: 1 addition & 0 deletions packages/postgrest-swr/src/mutate/use-delete-mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ function useDeleteMutation<
table: getTable(qb),
schema: qb.schema as string,
opts,
...opts,
});

return useMutation<R | null, PostgrestError, string, Partial<T['Row']>>(
Expand Down
1 change: 1 addition & 0 deletions packages/postgrest-swr/src/mutate/use-insert-mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ function useInsertMutation<
table: getTable(qb),
schema: qb.schema as string,
opts,
...opts,
});

return useMutation<R[] | null, PostgrestError, string, T['Insert'][]>(
Expand Down
1 change: 1 addition & 0 deletions packages/postgrest-swr/src/mutate/use-update-mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ function useUpdateMutation<
table: getTable(qb),
schema: qb.schema as string,
opts,
...opts,
});

return useSWRMutation<R | null, PostgrestError, string, T['Update']>(
Expand Down
1 change: 1 addition & 0 deletions packages/postgrest-swr/src/mutate/use-upsert-mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ function useUpsertMutation<
table: getTable(qb),
schema: qb.schema as string,
opts,
...opts,
});

return useMutation<R[] | null, PostgrestError, string, T['Insert'][]>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,14 @@ function useSubscriptionQuery<
table: filter.table,
schema: filter.schema,
opts,
...opts,
});
const upsertItem = useUpsertItem({
primaryKeys,
table: filter.table,
schema: filter.schema,
opts,
...opts,
});

useEffect(() => {
Expand Down
3 changes: 3 additions & 0 deletions packages/postgrest-swr/src/subscribe/use-subscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,14 @@ function useSubscription<T extends GenericTable>(
table: filter.table,
schema: filter.schema,
opts,
...opts,
});
const upsertItem = useUpsertItem({
primaryKeys,
table: filter.table,
schema: filter.schema,
opts,
...opts,
});

useEffect(() => {
Expand All @@ -77,6 +79,7 @@ function useSubscription<T extends GenericTable>(
REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT ||
payload.eventType === REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE
) {
console.log('upsert item');
await upsertItem(payload.new);
} else if (
payload.eventType === REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE
Expand Down

3 comments on commit bb2a667

@vercel
Copy link

@vercel vercel bot commented on bb2a667 Aug 8, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on bb2a667 Aug 8, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

supabase-cache-helpers-swr-demo – ./examples/swr

supabase-cache-helpers-swr-demo-git-main-psteinroe.vercel.app
supabase-cache-helpers-swr-demo-psteinroe.vercel.app
supabase-cache-helpers-swr.vercel.app

@vercel
Copy link

@vercel vercel bot commented on bb2a667 Aug 8, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

supabase-cache-helpers-react-query – ./examples/react-query

supabase-cache-helpers-react-query-git-main-psteinroe.vercel.app
supabase-cache-helpers-react-query-psteinroe.vercel.app
supabase-cache-helpers-react-query.vercel.app

Please sign in to comment.