Skip to content

Commit

Permalink
Make useMutation mutate stable
Browse files Browse the repository at this point in the history
  • Loading branch information
steida committed Oct 25, 2022
1 parent 3c0f43d commit 15fa758
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 15 deletions.
5 changes: 5 additions & 0 deletions .changeset/early-buses-shave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"evolu": patch
---

Make useMutation mutate stable
3 changes: 2 additions & 1 deletion packages/evolu/src/createHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,9 @@ export const createHooks = <S extends DbSchema>(
};
};

const mutate = db.createMutate<S>();
const useMutation: UseMutation<S> = () => ({
mutate: db.createMutate<S>(),
mutate,
});

return {
Expand Down
28 changes: 14 additions & 14 deletions packages/evolu/src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,15 +299,16 @@ const createNewCrdtMessages = (
)
);

export const createMutate = <S extends DbSchema>(): Mutate<S> => {
const queueRef = new ioRef.IORef<
readonly {
readonly messages: ReadonlyNonEmptyArray<NewCrdtMessage>;
readonly onCompleteId: Option<OnCompleteId>;
}[]
>(readonlyArray.empty);

return function mutate(table, { id, ...values }, onComplete) {
const mutateQueueRef = new ioRef.IORef<
readonly {
readonly messages: ReadonlyNonEmptyArray<NewCrdtMessage>;
readonly onCompleteId: Option<OnCompleteId>;
}[]
>(readonlyArray.empty);

export const createMutate =
<S extends DbSchema>(): Mutate<S> =>
(table, { id, ...values }, onComplete) => {
const isInsert = id == null;
// eslint-disable-next-line no-param-reassign
if (isInsert) id = createId() as never;
Expand All @@ -333,13 +334,13 @@ export const createMutate = <S extends DbSchema>(): Mutate<S> => {
})
);

const runQueueMicrotask = queueRef.read().length === 0;
queueRef.modify(readonlyArray.append({ messages, onCompleteId }))();
const runQueueMicrotask = mutateQueueRef.read().length === 0;
mutateQueueRef.modify(readonlyArray.append({ messages, onCompleteId }))();

if (runQueueMicrotask)
pipe(
queueRef.read,
io.chainFirst(() => queueRef.write([])),
mutateQueueRef.read,
io.chainFirst(() => mutateQueueRef.write([])),
io.map(readonlyNonEmptyArray.fromReadonlyArray),
ioOption.chainIOK((queue) =>
postDbWorkerInput({
Expand All @@ -362,7 +363,6 @@ export const createMutate = <S extends DbSchema>(): Mutate<S> => {

return { id } as never;
};
};

export const getOwner: Task<Owner> = owner;

Expand Down

1 comment on commit 15fa758

@vercel
Copy link

@vercel vercel bot commented on 15fa758 Oct 25, 2022

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:

evolu – ./

evolu-evolu.vercel.app
evolu.vercel.app
evolu-git-main-evolu.vercel.app
evolu.dev
www.evolu.dev

Please sign in to comment.