
Product
Introducing Pull Request Stories to Help Security Teams Track Supply Chain Risks
Socket’s new Pull Request Stories give security teams clear visibility into dependency risks and outcomes across scanned pull requests.
snap-query
Advanced tools
Snap Query is a minimalistic and type-safe library for creating custom query and mutation hooks in React. It leverages the power of nanostores, axios, and zod to provide a simple and efficient way to manage API requests and state in your application.
Snap Query is a minimalistic and type-safe library for creating custom query and mutation hooks in React. It leverages the power of nanostores, axios, and zod to provide a simple and efficient way to manage API requests and state in your application.
Install Snap Query via npm:
npm install snap-query
Snap Query provides a set of hooks for managing API requests and state in React applications. These hooks are built with type safety and simplicity in mind, ensuring that your data fetching and mutation logic is clean, maintainable, and reusable.
First, import the createQueryHook
function from Snap Query:
import { createQueryHook } from "snap-query";
Define a URL and a DTO (Data Transfer Object) using Zod:
import { z } from "zod";
// Define the URL for the API endpoint with a parameter placeholder
const url = '/test/:myPathParam';
// Define the structure of the response data using Zod for validation
const dto = z.object({
name: z.string(),
});
Create the query hook:
const [useQuery, emitQuery] = createQueryHook(
url,
{
defaultValidator: dto, // (Optional) Validator for response data
logLevel: 'debug', // (Optional) default to 'none'
// Additional axios request config options can be provided here
// method: 'post',
// baseURL: myBaseUrl,
},
axiosInstance // (Optional) custom axios instance
);
Use the query hook in your components:
import React, { useEffect } from "react";
export const TestComponent = () => {
const params = React.useMemo(() => ({
pathParams: { myPathParam: 'test' },
skip: false,
// Additional axios request config options
// method: 'post',
// baseURL: myBaseUrl,
}), []);
const queryResult = useQuery(params);
if (queryResult.isError) {
return (
<div>error</div>
);
}
return (
<div>
{queryResult.isLoading ? 'Loading...' : queryResult.data.name}
</div>
);
};
Import the createMutateHook
function:
import { createMutateHook } from "snap-query";
Create the mutation hook:
const useMutate = createMutateHook(
url,
{
defaultValidator: dto, // (Optional) Validator for response data
logLevel: 'debug', // (Optional) default to 'none'
// Additional axios request config options can be provided here
// method: 'post',
// baseURL: myBaseUrl,
},
axiosInstance // (Optional) custom axios instance
);
Use the mutation hook in your components:
import React from "react";
export const TestMutate = () => {
const [{ cancel, mutate, reset }, queryResult] = useMutate({
// Additional axios request config options can be provided here
// method: 'post',
// baseURL: myBaseUrl,
});
const onClick = () => {
mutate({ pathParams: { myPathParam: 'test' } });
};
if (queryResult.isError) {
return (
<div>error</div>
);
}
return (
<>
<button onClick={onClick}>Mutate</button>
<div>
{queryResult.isLoading ? 'Loading...' : queryResult.data.name}
</div>
</>
);
};
Snap Query supports React's Suspense for deferred loading of components.
Create a lazy hook:
import { createLazyHook } from "snap-query";
const useLazyUserQuery = createLazyHook(
url,
{
defaultValidator: dto, // (Optional) Validator for response data
logLevel: 'debug', // (Optional) default to 'none'
// Additional axios request config options can be provided here
// method: 'post',
// baseURL: myBaseUrl,
},
axiosInstance // (Optional) custom axios instance
);
Use it in your components:
import React, { Suspense, useMemo } from "react";
import { LazyResponse } from "snap-query";
const UserDataComponent = ({ resource }: { resource: LazyResponse<ResType> }) => {
const res = resource.read();
if (res?.error) {
return <div>Error</div>;
}
return (
<div>
<h1>{res?.data?.id}</h1>
<p>{res?.data?.title}</p>
</div>
);
};
const App = () => {
const [count, setCount] = React.useState(1);
const queryParams = useMemo(() => ({
pathParams: { id: count },
validator: ResDto,
// Additional axios request config options can be provided here
// method: 'post',
// baseURL: myBaseUrl,
}), [count]);
const lazyResult = useLazyUserQuery(queryParams);
return (
<Suspense fallback={<div>Loading...</div>}>
<UserDataComponent resource={lazyResult} />
</Suspense>
);
};
Pull requests are welcome. Please ensure you update tests as appropriate.
This project is licensed under the MIT License.
FAQs
Snap Query is a minimalistic and type-safe library for creating custom query and mutation hooks in React. It leverages the power of nanostores, axios, and zod to provide a simple and efficient way to manage API requests and state in your application.
We found that snap-query demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket’s new Pull Request Stories give security teams clear visibility into dependency risks and outcomes across scanned pull requests.
Research
/Security News
npm author Qix’s account was compromised, with malicious versions of popular packages like chalk-template, color-convert, and strip-ansi published.
Research
Four npm packages disguised as cryptographic tools steal developer credentials and send them to attacker-controlled Telegram infrastructure.