Skip to content

Commit

Permalink
feat: refreshable query atom (#19)
Browse files Browse the repository at this point in the history
* feat: refreshable query atom

* refactor: remove dependency on `atomWithRefresh`

* ci: bump Node to 18
  • Loading branch information
tien authored Mar 11, 2024
1 parent 1fe57e3 commit c897142
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 16 deletions.
2 changes: 1 addition & 1 deletion .codesandbox/ci.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"buildCommand": "compile",
"sandboxes": ["new", "react-typescript-react-ts"],
"node": "14"
"node": "18"
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
"html-webpack-plugin": "^5.5.3",
"jest": "^29.5.0",
"jest-environment-jsdom": "^29.5.0",
"jotai": "^2.2.1",
"jotai": "^2.7.0",
"microbundle": "^0.15.1",
"npm-run-all": "^4.1.5",
"prettier": "^2.8.8",
Expand Down
16 changes: 12 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 18 additions & 10 deletions src/createTRPCJotai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,24 @@ const atomWithQuery = <TProcedure extends AnyQueryProcedure, TClient>(
getOptions?: ValueOrGetter<TRPCRequestOptions & CustomOptions>,
) => {
type Output = inferProcedureOutput<TProcedure>;
const queryAtom = atom(async (get, { signal }) => {
const procedure = getProcedure(getClient(get), path);
const options = isGetter(getOptions) ? getOptions(get) : getOptions;
const input = await (isGetter(getInput) ? getInput(get) : getInput);
if (input === DISABLED) {
return options?.disabledOutput;
}
const output: Output = await procedure.query(input, { signal, ...options });
return output;
});
const refreshAtom = atom(0);
const queryAtom = atom(
async (get, { signal }) => {
get(refreshAtom);
const procedure = getProcedure(getClient(get), path);
const options = isGetter(getOptions) ? getOptions(get) : getOptions;
const input = await (isGetter(getInput) ? getInput(get) : getInput);
if (input === DISABLED) {
return options?.disabledOutput;
}
const output: Output = await procedure.query(input, {
signal,
...options,
});
return output;
},
(_, set) => set(refreshAtom, (counter) => counter + 1),
);
return queryAtom;
};

Expand Down

0 comments on commit c897142

Please sign in to comment.