Enable Dark Mode!
how-to-validate-api-responses-in-react-using-zod.jpg
By: Alan Joy

How to Validate API Responses in React Using Zod

Technical odoo React

When we build a React application, we often need to fetch data from an API. This data could be a list of users, products, blog posts, or other resources. However, we can't guarantee that the data returned by the API will always be in the format we expect. An API response can change over time, return incomplete data, or even fail to return the expected data. If our React app relies on this data and the response is not in the expected format, the app may encounter runtime errors that can be difficult to debug. This is where Zod comes in.

Zod is a TypeScript-first schema validation library that helps you to validate your data at runtime. So instead of trusting the API responses, we can verify that the data matches the structure our application expects before using it. In this blog, we will learn to use Zod validation, how to create the schemas for Zod, and how to safely handle both valid and invalid API responses.

What is Zod?

Zod is a schema validation library that will help in checking whether data matches the predefined structure. We will define the shape of our data once, and Zod will verify that any incoming data follows the structure. It can also provide clear error messages when the validations fail, making debugging much easier.

Install Zod

First, we need to install Zod in our React project. Use this command to install Zod

npm install zod

Create Your First Schema

Let's suppose our API returns user information. First, we need to create a schema describing how a valid user should look.

import { z } from "zod";
const userSchema = z.object({
 id: z.number(),
 name: z.string(),
 email: z.email(),
});

This schema tells Zod that

  • Id must be a number
  • Name must be a string
  • Email must be a valid email address

Any data that does not follow these rules will fail validation

Fetch and Validate the data

Next, fetch your user data

const response = await fetch("/api/users/1");
const data = await response.json();

Now, we can use zod’s safeParse() method to validate the response

const result = userSchema.safeParse(data);

There are parse() and safeParse() methods. The parse () method throws an error if the validation fails. safeParse returns an object containing either the validated data or the validation errors.

if (!result.success) {
 console.error(result.error);
 return;
}
const user = result.data;

Validating Arrays

Many APIs will return arrays instead of single objects. We can validate the entire array by wrapping our schema with z.array()

const usersSchema = z.array(userSchema);
const result = usersSchema.safeParse(data);

Making Fields Optional

Sometimes APIs don't always return all fields. We can make fields optional in the schema using optional()

const userSchema = z.object({
 id: z.number(),
 name: z.string(),
 email: z.email(),
 phone: z.string().optional(),
});

Providing Default Values

We can also define default values as below:

const userSchema = z.object({
 name: z.string(),
 role: z.string().default("User"),
});

Validating API responses is an important step in building a reliable React application. With Zod, we can verify the data before using it in the components. Zod can also help prevent runtime errors, improve debugging, and make our application more resilient to unexpected api changes.

To read more about How to Implement Optimistic Updates in React with TanStack Query, refer to our blog How to Implement Optimistic Updates in React with TanStack Query.


Frequently Asked Questions

Why should I validate API responses in React?

It helps prevent runtime errors by ensuring the data matches the format your application expects.

What is the difference between parse() and safeParse() in Zod?

parse() throws an error on invalid data, while safeParse() returns a success flag and validation result without throwing.

Can I use Zod without TypeScript?

Yes. Although Zod is TypeScript-first, it works perfectly with JavaScript projects as well.

If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



WhatsApp