T
TanStack3y ago
foreign-sapphire

How to handle zodErrors?

Anyone here using zod and react query? How are you handling zod errors? I assume with a try/catch but where in the code should it be handled?
import z from "zod";

export const userSchema = z.array(
z.object({
id: z.number(),
name: z.number(),
})
);


export const useFetchUsers = () => {
return useQuery([users.fetchUsers], async () => {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/users"
);
return userSchema.parse(response.data);
});
};


export const App = () => {
const { data: usersData } = useFetchUsers();
return (
<>
{usersData?.map((user) => (
<ul>
<li key={user.id}>{user.name}</li>
</ul>
))}
</>
);
};


ZodError: [
{
"code": "invalid_type",
"expected": "number",
"received": "string",
"path": [
0,
"name"
],
"message": "Expected number, received string"
},
import z from "zod";

export const userSchema = z.array(
z.object({
id: z.number(),
name: z.number(),
})
);


export const useFetchUsers = () => {
return useQuery([users.fetchUsers], async () => {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/users"
);
return userSchema.parse(response.data);
});
};


export const App = () => {
const { data: usersData } = useFetchUsers();
return (
<>
{usersData?.map((user) => (
<ul>
<li key={user.id}>{user.name}</li>
</ul>
))}
</>
);
};


ZodError: [
{
"code": "invalid_type",
"expected": "number",
"received": "string",
"path": [
0,
"name"
],
"message": "Expected number, received string"
},
1 Reply
sunny-green
sunny-green3y ago
No try/catch necessary - you'll get those errors in the error field returned from useQuery

Did you find this page helpful?