An open API service indexing awesome lists of open source software.

https://github.com/ecyrbe/zodios-react

React hooks for zodios
https://github.com/ecyrbe/zodios-react

Last synced: over 1 year ago
JSON representation

React hooks for zodios

Awesome Lists containing this project

README

          

Zodios React




Zodios logo




React hooks for zodios backed by react-query





langue typescript


npm


GitHub

GitHub Workflow Status

# Install

```bash
> npm install @zodios/react
```

or

```bash
> yarn add @zodios/react
```

# Usage

Zodios comes with a Query and Mutation hook helper.
It's a thin wrapper around React-Query but with zodios auto completion.

Zodios query hook also returns an invalidation helper to allow you to reset react query cache easily

```typescript
import React from "react";
import { QueryClient, QueryClientProvider } from "react-query";
import { Zodios, asApi } from "@zodios/core";
import { ZodiosHooks } from "@zodios/react";
import { z } from "zod";

// you can define schema before declaring the API to get back the type
const userSchema = z
.object({
id: z.number(),
name: z.string(),
})
.required();

const createUserSchema = z
.object({
name: z.string(),
})
.required();

const usersSchema = z.array(userSchema);

// you can then get back the types
type User = z.infer;
type Users = z.infer;

const api = asApi([
{
method: "get",
path: "/users",
description: "Get all users",
parameters: [
{
name: "q",
type: "Query",
schema: z.string(),
},
{
name: "page",
type: "Query",
schema: z.string().optional(),
},
],
response: usersSchema,
},
{
method: "get",
path: "/users/:id",
description: "Get a user",
response: userSchema,
},
{
method: "post",
path: "/users",
description: "Create a user",
parameters: [
{
name: "body",
type: "Body",
schema: createUserSchema,
},
],
response: userSchema,
},
]);
const baseUrl = "https://jsonplaceholder.typicode.com";

const zodios = new Zodios(baseUrl, api);
const zodiosHooks = new ZodiosHooks("jsonplaceholder", zodios);

const Users = () => {
const {
data: users,
isLoading,
error,
invalidate: invalidateUsers, // zodios also provides invalidation helpers
} = zodiosHooks.useQuery("/users");
const { mutate } = zodiosHooks.useMutation("post", "/users", undefined, {
onSuccess: () => invalidateUsers(),
});

return (
<>

Users


mutate({ name: "john doe" })}>add user
{isLoading &&
Loading...
}
{error &&
Error: {(error as Error).message}
}
{users && (

    {users.map((user) => (
  • {user.name}

  • ))}

)}
>
);
};

// on another file
const queryClient = new QueryClient();

export const App = () => {
return (



);
};
```