{"id":7486,"date":"2023-11-08T13:12:25","date_gmt":"2023-11-08T13:12:25","guid":{"rendered":"https:\/\/dianapps.com\/blog\/?p=7486"},"modified":"2023-11-08T13:12:25","modified_gmt":"2023-11-08T13:12:25","slug":"how-to-conduct-api-response-validation-in-react","status":"publish","type":"post","link":"https:\/\/www.dianapps.com\/blog\/how-to-conduct-api-response-validation-in-react\/","title":{"rendered":"How To Conduct API Response Validation In React?"},"content":{"rendered":"<p><span style=\"font-weight: 400;\">Welcome to a journey where practical knowledge meets React development. Beyond the lines of code, we&#8217;ll explore the art of crafting user-friendly interfaces and ensuring that the API responses fulfill our expectations.\u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400;\">But what\u2019s the need for validation?<\/span><\/p>\n<p><span style=\"font-weight: 400;\">In the world of frontend JavaScript applications, having a robust tool for validating and identifying inconsistencies in backend responses is essential. Imagine anticipating one data format, only to receive an empty response from the backend. How can the frontend detect and handle such a scenario? Let&#8217;s dig deeper into this!<\/span><\/p>\n<h1><span class=\"ez-toc-section\" id=\"What-is-API-Response-Validation-in-React\"><\/span><span style=\"font-weight: 400;\">What is API Response Validation in React?<\/span><span class=\"ez-toc-section-end\"><\/span><\/h1>\n<p><span style=\"font-weight: 400;\">API response validation in React is a crucial process of checking and confirming that the data received from an external source, typically an API (Application Programming Interface), meets the expected format, structure, and security standards within a React application.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">In simpler terms, it&#8217;s like making sure that the information you get from an API is trustworthy, accurate, and safe to use in your <\/span>React app Development<span style=\"font-weight: 400;\">. This validation process helps prevent security vulnerabilities and data errors and ensures that your application works with the data as intended. It often involves using tools, libraries, and coding practices to verify that the API responses align with what your app needs.<\/span><\/p>\n<h2><span class=\"ez-toc-section\" id=\"Tools-and-Libraries-for-API-Response-Validation\"><\/span><span style=\"font-weight: 400;\">Tools and Libraries for API Response Validation<\/span><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p><span style=\"font-weight: 400;\">In React apps, you can use several tools to make sure the data you get from APIs is correct and secure. Here&#8217;s how these tools help:<\/span><\/p>\n<h3><span class=\"ez-toc-section\" id=\"1-TypeScript\"><\/span><span style=\"font-weight: 400;\">1. TypeScript:<\/span><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">TypeScript is like supercharged JavaScript.<\/span><\/li>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">It lets you say exactly what kind of data you expect from an API.<\/span><\/li>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">In React Native 0.71, you have <\/span><a href=\"https:\/\/dianapps.com\/blog\/react-native-0-71-flexbox-gap-typescript-and-its-first-class-support\/\"><span style=\"font-weight: 400;\">TypeScript with first-class support<\/span><\/a><span style=\"font-weight: 400;\"> and new features like Flexbox Gap.<\/span><\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"2-Redux-Toolkit\"><\/span><span style=\"font-weight: 400;\">2. Redux Toolkit:<\/span><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">Redux Toolkit makes handling data in React easier.<\/span><\/li>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">You can use it to define how to handle API responses.<\/span><\/li>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">With TypeScript, you can be sure your code works with the right data types.<\/span><\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"3-Redux-Saga-Typed-Redux-Saga\"><\/span><span style=\"font-weight: 400;\">3. Redux Saga + Typed Redux Saga:<\/span><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">Redux Saga helps with things like API calls.<\/span><\/li>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">Typed Redux Saga makes it even safer with TypeScript.<\/span><\/li>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">You can make sure your code gets and uses the right data types.<\/span><\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"4-Apisauce\"><\/span><span style=\"font-weight: 400;\">4. Apisauce:<\/span><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">Apisauce helps you talk to APIs in a smart way.<\/span><\/li>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">You can set it up to check and change API data.<\/span><\/li>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">With TypeScript, you can define what the API response should look like.<\/span><\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"5-Superstruct\"><\/span><span style=\"font-weight: 400;\">5. Superstruct:<\/span><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">Superstruct checks if data matches your rules.<\/span><\/li>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">You can tell it how API responses should look.<\/span><\/li>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">If something&#8217;s wrong, Superstruct will notify you.<\/span><\/li>\n<\/ul>\n<p><span style=\"font-weight: 400;\">By using these tools, along with TypeScript, you make sure your app gets the right data from APIs. TypeScript helps find mistakes early, and tools like Superstruct and Apisauce keep your data safe. Redux Toolkit and Redux Saga make handling data in React easy and secure.<\/span><\/p>\n<h2><span class=\"ez-toc-section\" id=\"Security-aspects-of-API-response-validation\"><\/span><span style=\"font-weight: 400;\">Security aspects of API response validation<\/span><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p><span style=\"font-weight: 400;\">API response validation is essential for ensuring the security in the process of mobile app development, especially when dealing with APIs. Security is a top priority, and there are key aspects to keep in mind:<\/span><\/p>\n<h3><span class=\"ez-toc-section\" id=\"1-Data-Integrity\"><\/span><span style=\"font-weight: 400;\">1. Data Integrity<\/span><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><span style=\"font-weight: 400;\">When you validate API responses, you&#8217;re essentially checking that the data coming from external sources is accurate and hasn&#8217;t been tampered with during transmission. This prevents malicious actors from tampering with the data before it reaches your application.<\/span><\/p>\n<h3><span class=\"ez-toc-section\" id=\"2-Injection-Attacks\"><\/span><span style=\"font-weight: 400;\">2. Injection Attacks<\/span><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><span style=\"font-weight: 400;\">Without proper validation, APIs can be vulnerable to injection attacks like SQL injection or Cross-Site Scripting (XSS). Validation helps filter out potentially harmful input and keeps your application safe.<\/span><\/p>\n<h3><span class=\"ez-toc-section\" id=\"3-Authorization\"><\/span><span style=\"font-weight: 400;\">3. Authorization<\/span><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><span style=\"font-weight: 400;\">Validating API responses includes verifying if the user making the request has the proper authorization to access the data. Unauthorized access can lead to serious data breaches, so this is crucial.<\/span><\/p>\n<h3><span class=\"ez-toc-section\" id=\"4-Secure-Communication\"><\/span><span style=\"font-weight: 400;\">4. Secure Communication<\/span><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><span style=\"font-weight: 400;\">APIs should always use secure protocols like HTTPS to encrypt data during transit. Validating responses ensures that the communication between your app and the API remains secure.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Also read about how to <\/span><a href=\"https:\/\/dianapps.com\/blog\/integrating-apis-in-react-native-for-enhanced-functionality\/\"><span style=\"font-weight: 400;\">integrate APIs in React Native<\/span><\/a><span style=\"font-weight: 400;\"> for enhanced functionality.\u00a0<\/span><\/p>\n<h2><span class=\"ez-toc-section\" id=\"Process-of-API-Response-Validation-in-React\"><\/span><span style=\"font-weight: 400;\">Process of API Response Validation in React<\/span><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Project-Configuration\"><\/span><span style=\"font-weight: 400;\">Project Configuration<\/span><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><span style=\"font-weight: 400;\">The first step is configuring your project. After creating your app from the basic template, you&#8217;ll need to add some libraries to it. You can either manually add them to your package.json file or use Yarn for installation.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Here are the libraries and their versions used in the project:<\/span><\/p>\n<p><strong>\/\/ package.json<\/strong><\/p>\n<p><strong>&#8230;<\/strong><\/p>\n<p><strong>&#8220;dependencies&#8221;: {<\/strong><\/p>\n<p><strong>\u00a0\u00a0&#8220;@reduxjs\/toolkit&#8221;: &#8220;1.9.1&#8221;,<\/strong><\/p>\n<p><strong>\u00a0\u00a0&#8220;apisauce&#8221;: &#8220;1.1.2&#8221;,<\/strong><\/p>\n<p><strong>\u00a0\u00a0&#8220;react&#8221;: &#8220;18.2.0&#8221;,<\/strong><\/p>\n<p><strong>\u00a0\u00a0&#8220;react-redux&#8221;: &#8220;8.0.5&#8221;,<\/strong><\/p>\n<p><strong>\u00a0\u00a0&#8220;redux&#8221;: &#8220;4.2.1&#8221;,<\/strong><\/p>\n<p><strong>\u00a0\u00a0&#8220;redux-saga&#8221;: &#8220;1.2.2&#8221;,<\/strong><\/p>\n<p><strong>\u00a0\u00a0&#8220;superstruct&#8221;: &#8220;1.0.3&#8221;,<\/strong><\/p>\n<p><strong>\u00a0\u00a0&#8220;typed-redux-saga&#8221;: &#8220;1.5.0&#8221;,<\/strong><\/p>\n<p><strong>},<\/strong><\/p>\n<p><strong>&#8230;<\/strong><\/p>\n<p><span style=\"font-weight: 400;\">You can easily include these libraries to your project with yarn<\/span><\/p>\n<h3><span class=\"ez-toc-section\" id=\"Implementation\"><\/span><span style=\"font-weight: 400;\">Implementation<\/span><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><span style=\"font-weight: 400;\">Initially, we need to generate our User schema and define all the types required for using it within Redux, Redux-Saga, and the API.<\/span><\/p>\n<pre class=\"theme:github font-size:14 nums:false lang:default decode:true\">\/\/ exampleSchema.ts\r\n\r\n\/\/ You can explore the documentation for superstruct to create more intricate schemas.\r\n\r\n\/\/ For now, we'll start with a straightforward one.\r\n\r\nimport { Infer, number, string, type } from 'superstruct';\r\n\r\n\/\/ Define a schema for the user to ensure validation of all expected fields.\r\n\r\nexport const UserSchema = type({\r\n\r\n\u00a0\u00a0id: string(),\r\n\r\n\u00a0\u00a0name: string(),\r\n\r\n\u00a0\u00a0age: number(),\r\n\r\n});\r\n\r\n\/\/ Infer the type from the schema to create a standard TypeScript type.\r\n\r\nexport type User = Infer&lt;typeof UserSchema&gt;;\r\n\r\n\/\/ Extract the ID type from User for added convenience.\r\n\r\nexport type UserID = User['id'];<\/pre>\n<p><span style=\"font-weight: 400;\">Next, we can create a Redux slice and connect it with our rootReducer:<\/span><\/p>\n<pre class=\"theme:github font-size:14 nums:false lang:default decode:true\">\/\/ exampleSlice.ts\r\n\r\n\/\/ This file contains the Redux slice for the \"example\" feature\r\n\r\nimport { CaseReducer, createSlice, PayloadAction } from '@reduxjs\/toolkit';\r\n\r\nimport { User } from '.\/exampleSchema';\r\n\r\n\/\/ Define the user and error types for this Redux slice\r\n\r\ntype ExampleState = {\r\n\r\n\u00a0\u00a0user: User | null;\r\n\r\n\u00a0\u00a0error: string | null;\r\n\r\n};\r\n\r\n\/\/ Initial values for the current slice\r\n\r\nconst INITIAL_STATE: ExampleState = {\r\n\r\n\u00a0\u00a0user: null,\r\n\r\n\u00a0\u00a0error: null,\r\n\r\n};\r\n\r\n\/\/ We will use this action to trigger our saga flow and initiate user fetching\r\n\r\nconst getUser: CaseReducer&lt;ExampleState&gt; = () =&gt; {};\r\n\r\n\/\/ We will use this action to save the received user to the store\r\n\r\nexport type GetUserSucceededAction = PayloadAction&lt;User&gt;;\r\n\r\nconst getUserSucceeded: CaseReducer&lt;ExampleState, GetUserSucceededAction&gt; = (state, { payload: user }) =&gt; {\r\n\r\n\u00a0\u00a0state.user = user;\r\n\r\n};\r\n\r\n\/\/ We will use this action to save the error to the store\r\n\r\nconst getUserFailed: CaseReducer&lt;ExampleState, PayloadAction&lt;string&gt;&gt; = (state, { payload: error }) =&gt; {\r\n\r\n\u00a0\u00a0state.error = error;\r\n\r\n};\r\n\r\n\/\/ Create a slice for the \"example\" feature with all the CaseReducers defined above\r\n\r\nconst exampleSlice = createSlice({\r\n\r\n\u00a0\u00a0name: 'example',\r\n\r\n\u00a0\u00a0initialState: INITIAL_STATE,\r\n\r\n\u00a0\u00a0reducers: {\r\n\r\n\u00a0\u00a0\u00a0\u00a0getUser,\r\n\r\n\u00a0\u00a0\u00a0\u00a0getUserSucceeded,\r\n\r\n\u00a0\u00a0\u00a0\u00a0getUserFailed,\r\n\r\n\u00a0\u00a0},\r\n\r\n});\r\n\r\n\/\/ Export all actions with an `Action` suffix to avoid naming conflicts\r\n\r\nexport const {\r\n\r\n\u00a0\u00a0getUser: getUserAction,\r\n\r\n\u00a0\u00a0getUserSucceeded: getUserSucceededAction,\r\n\r\n\u00a0\u00a0getUserFailed: getUserFailedAction,\r\n\r\n} = exampleSlice.actions;<\/pre>\n<p><span style=\"font-weight: 400;\">Defining the core API and adding schema validation for different request types, such as POST, GET, PUT, PATCH, and DELETE, is about strengthening the API&#8217;s foundation. It means implementing a validation system that checks if the data sent to the API matches a predetermined structure. Let&#8217;s break down how this validation process works for each type of request.<\/span><\/p>\n<ul>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">POST Request<\/span><\/li>\n<\/ul>\n<p><span style=\"font-weight: 400;\">When data is being created or added (e.g., submitting a new record), the schema validation checks that the data provided follows the expected format and includes all required fields.<\/span><\/p>\n<ul>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">GET Request<\/span><\/li>\n<\/ul>\n<p><span style=\"font-weight: 400;\">For retrieving data, schema validation can ensure that query parameters and filters are correctly formatted and that the response data meets the expected schema.<\/span><\/p>\n<ul>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">PUT Request<\/span><\/li>\n<\/ul>\n<p><span style=\"font-weight: 400;\">When updating an existing resource, the validation ensures that the data sent for the update aligns with the defined schema.<\/span><\/p>\n<ul>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">PATCH Request<\/span><\/li>\n<\/ul>\n<p><span style=\"font-weight: 400;\">Similar to PUT requests, PATCH requests validate the partial updates made to a resource against the schema.<\/span><\/p>\n<ul>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">DELETE Request<\/span><\/li>\n<\/ul>\n<p><span style=\"font-weight: 400;\">While DELETE requests don&#8217;t usually involve data validation (as they are about resource removal), they can be validated for proper authorization and adherence to any relevant constraints.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Here\u2019s an example:\u00a0<\/span><\/p>\n<pre class=\"theme:github font-size:14 nums:false lang:default decode:true\">\/\/ apiClient.ts\r\n\r\n\/\/ Basic template from \"apisauce\" library\r\n\r\nimport apisauce, { ApisauceInstance } from 'apisauce';\r\n\r\nimport { API_BASE_URL, API_DEFAULT_HEADERS, API_TIMEOUT } from '#constants';\r\n\r\nexport const apiClient: ApisauceInstance = apisauce.create({\r\n\r\n\u00a0\u00a0baseURL: API_BASE_URL,\r\n\r\n\u00a0\u00a0timeout: API_TIMEOUT,\r\n\r\n\u00a0\u00a0headers: API_DEFAULT_HEADERS,\r\n\r\n});\r\n\r\nexport const setAuthHeader = (token: string) =&gt; {\r\n\r\n\u00a0\u00a0apiClient.setHeader('Authorization', `Bearer ${token}`);\r\n\r\n};\r\n\r\nexport const clearAuthHeader = () =&gt; {\r\n\r\n\u00a0\u00a0apiClient.deleteHeader('Authorization');\r\n\r\n};\r\n\r\n\/\/ apiClientWithSchemaValidation.ts\r\n\r\n\/\/ Our custom modification for apiClient to check all responses from the backend!\r\n\r\nimport { ApiResponse } from 'apisauce';\r\n\r\n\/\/ apisauce also includes \"axios\" library\r\n\r\nimport { AxiosRequestConfig, Method } from 'axios';\r\n\r\nimport { create, Struct } from 'superstruct';\r\n\r\nimport { apiClient } from '.\/apiClient';\r\n\r\nconst apiRequestWithSchemaValidation = async &lt;TExpectedData&gt;(\r\n\r\n\u00a0\u00a0params: Parameters&lt;typeof apiClient.any&lt;TExpectedData&gt;&gt;,\r\n\r\n\u00a0\u00a0schema?: Struct&lt;Any&gt;,\r\n\r\n): Promise&lt;ApiResponse&lt;TExpectedData&gt;&gt; =&gt; {\r\n\r\n\u00a0\u00a0const [requestConfig] = params;\r\n\r\n\u00a0\u00a0const response = await apiClient.any&lt;TExpectedData&gt;(requestConfig);\r\n\r\n\u00a0\u00a0const actualResponseData = response.data as TExpectedData;\r\n\r\n\u00a0\u00a0\/\/ Only if schema is passed here\r\n\r\n\u00a0\u00a0if (schema) {\r\n\r\n\u00a0\u00a0\u00a0\u00a0try {\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\/\/ Validation\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0create(actualResponseData, schema);\r\n\r\n\u00a0\u00a0\u00a0\u00a0} catch (error) {\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\/\/ If there any mistakes in response - this statement will catch all for us\r\n\r\n\r\n\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\/\/ You can add any analytic handlers here\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0console.log(`Superstruct validation error, URL: ${requestConfig.baseURL}${requestConfig.url}`);\r\n\r\n\u00a0\u00a0\u00a0\u00a0}\r\n\r\n\u00a0\u00a0}\r\n\r\n\u00a0\u00a0return response;\r\n\r\n};\r\n\r\nconst createRequestWithDataHandler =\r\n\r\n\u00a0\u00a0(method: Method) =&gt;\r\n\r\n\u00a0\u00a0&lt;TSuccessResponse&gt;(url: string, data?: Any, schema?: Struct&lt;Any&gt;, additionalConfig: AxiosRequestConfig = {}) =&gt;\r\n\r\n\u00a0\u00a0\u00a0\u00a0apiRequestWithSchemaValidation&lt;TSuccessResponse&gt;(\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0[\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0{\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0url,\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0method,\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0data,\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0...additionalConfig,\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0},\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0],\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0schema,\r\n\r\n\u00a0\u00a0\u00a0\u00a0);\r\n\r\n\r\n\r\n\r\nexport const apiClientWithSchemaValidation = {\r\n\r\n\u00a0\u00a0\/\/ Validated GET\r\n\r\n\u00a0\u00a0get: &lt;TSuccessResponse&gt;(url: string, schema?: Struct&lt;Any&gt;, additionalConfig: AxiosRequestConfig = {}) =&gt;\r\n\r\n\u00a0\u00a0\u00a0\u00a0apiRequestWithSchemaValidation&lt;TSuccessResponse&gt;(\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0[\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0{\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0url,\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0method: 'GET',\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0...additionalConfig,\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0},\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0],\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0schema,\r\n\r\n\u00a0\u00a0\u00a0\u00a0),\r\n\r\n\r\n\r\n\r\n\u00a0\u00a0\/\/ Validated POST\r\n\r\n\u00a0\u00a0post: createRequestWithDataHandler('POST'),\r\n\r\n\r\n\r\n\r\n\u00a0\u00a0\/\/ Validated PUT\r\n\r\n\u00a0\u00a0put: createRequestWithDataHandler('PUT'),\r\n\r\n\r\n\r\n\r\n\u00a0\u00a0\/\/ Validated DELETE\r\n\r\n\u00a0\u00a0delete: createRequestWithDataHandler('DELETE'),\r\n\r\n};<\/pre>\n<p><span style=\"font-weight: 400;\">Defining apiInstance in our example:<\/span><span style=\"font-weight: 400;\"><br \/>\n<\/span><\/p>\n<p><span style=\"font-weight: 400;\">So, apiInstance essentially means an instance of an API. In the context of code or development, it usually represents an object or variable that has been instantiated from an API class or module. This instance can then be used to make API requests, handle responses, and interact with the API as needed within a software application.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">The specific usage and implementation of apiInstance can vary depending on the programming language, framework, and the particular API being used in a given project.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Let\u2019s define an apiInstance for our &#8216;example&#8217; segment of APIs:<\/span><\/p>\n<pre class=\"theme:github font-size:14 nums:false lang:default decode:true\">\/\/ exampleApi.ts\r\n\r\nimport { User, UserSchema } from '.\/exampleSchema';\r\n\r\nimport { apiClientWithSchemaValidation } from '.\/apiClientWithSchemaValidation';\r\n\r\n\/\/ Call our \"apiClientWithSchemaValidation.get, define type param as User and schema\u00a0\r\n\r\nconst getUser = () =&gt; apiClientWithSchemaValidation.get&lt;User&gt;('api\/auth\/user', UserSchema);\r\n\r\nexport const exampleApi = {\r\n\r\n\u00a0\u00a0getUser,\r\n\r\n};<\/pre>\n<p><span style=\"font-weight: 400;\">And the final exampleSaga.ts :<\/span><\/p>\n<pre class=\"theme:github font-size:14 nums:false lang:default decode:true\">import { call, put, takeLatest } from 'typed-redux-saga';\r\n\r\n\/\/ apiInstance from the code snippets above\r\n\r\nimport { apiInstance } from '#services\/api';\r\n\r\n\/\/ RootState where we connect our exampleSlice.reducer\r\n\r\nimport { getUserAction, getUserFailedAction, getUserSucceededAction } from '.\/exampleSlice';\r\n\r\nfunction* getUserWorker() {\r\n\r\n\u00a0\u00a0\/\/ After this call we'll get the console.log error if there are any mistakes in response!\r\n\r\n\u00a0\u00a0const response = yield* call(apiInstance.example.getUser);\r\n\r\n\u00a0\u00a0if (response.ok &amp;&amp; response.data) {\r\n\r\n\u00a0\u00a0\u00a0\u00a0yield* put(getUserSucceededAction(response.data));\r\n\r\n\u00a0\u00a0} else {\r\n\r\n\u00a0\u00a0\u00a0\u00a0yield* put(getUserFailedAction('Something went wrong'));\r\n\r\n\u00a0\u00a0}\r\n\r\n}\r\n\r\n\/\/ Connect this to your root saga\r\n\r\nexport function* exampleSaga() {\r\n\r\n\u00a0\u00a0yield* takeLatest(getUserAction, getUserWorker);\r\n\r\n}<\/pre>\n<p><span style=\"font-weight: 400;\">If you need to check the result, you can easily dispatch an action from any component:<\/span><\/p>\n<pre class=\"theme:github font-size:14 nums:false lang:default decode:true\">\/\/ MyComponents.tsx\r\n\r\nimport { useEffect } from 'react';\r\n\r\nimport { getUserAction } from '.\/exampleSlice';\r\n\r\nexport const MyComponent = () =&gt; {\r\n\r\n\u00a0\u00a0useEffect(() =&gt; {\r\n\r\n\u00a0\u00a0\u00a0\u00a0\/\/ Make this call only on component mount once\r\n\r\n\u00a0\u00a0\u00a0\u00a0dispatch(getUserAction());\r\n\r\n\u00a0\u00a0}, []);\r\n\r\n\u00a0\u00a0return &lt;div&gt;&lt;\/div&gt;;\r\n\r\n}<\/pre>\n<p><a href=\"https:\/\/medium.com\/@xbstrxct\/react-api-response-validation-44d51575671f\"><span style=\"font-weight: 400;\">Code Source<\/span><\/a><\/p>\n<h2><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span><span style=\"font-weight: 400;\">Conclusion<\/span><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p><span style=\"font-weight: 400;\">As we wrap up our journey in building a robust mobile application, we&#8217;ve explored the crucial process of API response validation and its role in refreshing our application&#8217;s reliability. Through the effective use of tools such as TypeScript, Redux, Redux-Saga, and Superstruct, we&#8217;ve not only established a strong foundation but also paved the way for structured and validated responses from our backend. We&#8217;ve seamlessly integrated these components into our Redux slices and API calls, ensuring that our frontend remains resilient in the face of ever-changing backend responses.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">With these best practices efficiently applied, you&#8217;re now well-prepared to guarantee that your frontend delivers a seamless user experience, whether you&#8217;re fetching data or transmitting updates. The confidence derived from working with validated API responses is an invaluable asset.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">But remember, the field of frontend development is a dynamic one, constantly evolving and presenting new challenges. So, as you continue your development journey, consider these tools and techniques as your stepping stones, and keep exploring and expanding your skills to create powerful and reliable applications. If you\u2019re facing any difficulty in conducting the above process, then contact experts from our <\/span><a href=\"https:\/\/dianapps.com\/react-native-app-development\"><b>React development company<\/b><\/a><span style=\"font-weight: 400;\">. They will help you in understanding the complexities of the process.<\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Welcome to a journey where practical knowledge meets React development. Beyond the lines of code, we&#8217;ll explore the art of crafting user-friendly interfaces and ensuring that the API responses fulfill our expectations.\u00a0 But what\u2019s the need for validation? In the world of frontend JavaScript applications, having a robust tool for validating and identifying inconsistencies in [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":7499,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_wp_applaud_exclude":false,"footnotes":""},"categories":[3],"tags":[409,408],"class_list":["post-7486","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-app-development","tag-react-app-development","tag-validate-api-response-in-react"],"featured_image_src":{"landsacpe":["https:\/\/www.dianapps.com\/blog\/wp-content\/uploads\/2023\/11\/Frame-3.png",791,445,false],"list":["https:\/\/www.dianapps.com\/blog\/wp-content\/uploads\/2023\/11\/Frame-3.png",463,260,false],"medium":["https:\/\/www.dianapps.com\/blog\/wp-content\/uploads\/2023\/11\/Frame-3.png",300,169,false],"full":["https:\/\/www.dianapps.com\/blog\/wp-content\/uploads\/2023\/11\/Frame-3.png",1536,864,false]},"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v20.12 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How To Conduct API Response Validation In React?<\/title>\n<meta name=\"description\" content=\"Do you know how to conduct API response validation in React? Here&#039;s a complete guide to successfully carry out the process to validate API response in React.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.dianapps.com\/blog\/how-to-conduct-api-response-validation-in-react\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How To Conduct API Response Validation In React?\" \/>\n<meta property=\"og:description\" content=\"Do you know how to conduct API response validation in React? Here&#039;s a complete guide to successfully carry out the process to validate API response in React.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.dianapps.com\/blog\/how-to-conduct-api-response-validation-in-react\/\" \/>\n<meta property=\"og:site_name\" content=\"Learn About Digital Transformation &amp; Development | DianApps Blog\" \/>\n<meta property=\"article:published_time\" content=\"2023-11-08T13:12:25+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.dianapps.com\/blog\/wp-content\/uploads\/2023\/11\/Frame-3.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1536\" \/>\n\t<meta property=\"og:image:height\" content=\"864\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Vikash Soni\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Vikash Soni\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How To Conduct API Response Validation In React?","description":"Do you know how to conduct API response validation in React? Here's a complete guide to successfully carry out the process to validate API response in React.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.dianapps.com\/blog\/how-to-conduct-api-response-validation-in-react\/","og_locale":"en_US","og_type":"article","og_title":"How To Conduct API Response Validation In React?","og_description":"Do you know how to conduct API response validation in React? Here's a complete guide to successfully carry out the process to validate API response in React.","og_url":"https:\/\/www.dianapps.com\/blog\/how-to-conduct-api-response-validation-in-react\/","og_site_name":"Learn About Digital Transformation &amp; Development | DianApps Blog","article_published_time":"2023-11-08T13:12:25+00:00","og_image":[{"width":1536,"height":864,"url":"https:\/\/www.dianapps.com\/blog\/wp-content\/uploads\/2023\/11\/Frame-3.png","type":"image\/png"}],"author":"Vikash Soni","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Vikash Soni","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.dianapps.com\/blog\/how-to-conduct-api-response-validation-in-react\/","url":"https:\/\/www.dianapps.com\/blog\/how-to-conduct-api-response-validation-in-react\/","name":"How To Conduct API Response Validation In React?","isPartOf":{"@id":"https:\/\/www.dianapps.com\/blog\/#website"},"datePublished":"2023-11-08T13:12:25+00:00","dateModified":"2023-11-08T13:12:25+00:00","author":{"@id":"https:\/\/www.dianapps.com\/blog\/#\/schema\/person\/0126fafc83e42bece2acbfe92f7d0f4f"},"description":"Do you know how to conduct API response validation in React? Here's a complete guide to successfully carry out the process to validate API response in React.","breadcrumb":{"@id":"https:\/\/www.dianapps.com\/blog\/how-to-conduct-api-response-validation-in-react\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.dianapps.com\/blog\/how-to-conduct-api-response-validation-in-react\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.dianapps.com\/blog\/how-to-conduct-api-response-validation-in-react\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.dianapps.com\/blog\/"},{"@type":"ListItem","position":2,"name":"How To Conduct API Response Validation In React?"}]},{"@type":"WebSite","@id":"https:\/\/www.dianapps.com\/blog\/#website","url":"https:\/\/www.dianapps.com\/blog\/","name":"Learn About Digital Transformation &amp; Development | DianApps Blog","description":"Dianapps","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.dianapps.com\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.dianapps.com\/blog\/#\/schema\/person\/0126fafc83e42bece2acbfe92f7d0f4f","name":"Vikash Soni","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.dianapps.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/dianapps.com\/blog\/wp-content\/uploads\/2022\/07\/cropped-vikash-96x96.png","contentUrl":"https:\/\/dianapps.com\/blog\/wp-content\/uploads\/2022\/07\/cropped-vikash-96x96.png","caption":"Vikash Soni"},"description":"Vikash Soni, the visionary CEO and Co-founder of DianApps. With his profound expertise in Android and iOS app development, he leads the team to deliver top-notch solutions to clients worldwide. Under his guidance, the company has achieved remarkable success, earning a reputation as a leading web and mobile app development company.","sameAs":["https:\/\/www.linkedin.com\/in\/vikash-soni-59726530\/"],"url":"https:\/\/www.dianapps.com\/blog\/author\/infodianapps-com\/"}]}},"_links":{"self":[{"href":"https:\/\/www.dianapps.com\/blog\/wp-json\/wp\/v2\/posts\/7486","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.dianapps.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.dianapps.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.dianapps.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.dianapps.com\/blog\/wp-json\/wp\/v2\/comments?post=7486"}],"version-history":[{"count":3,"href":"https:\/\/www.dianapps.com\/blog\/wp-json\/wp\/v2\/posts\/7486\/revisions"}],"predecessor-version":[{"id":7501,"href":"https:\/\/www.dianapps.com\/blog\/wp-json\/wp\/v2\/posts\/7486\/revisions\/7501"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.dianapps.com\/blog\/wp-json\/wp\/v2\/media\/7499"}],"wp:attachment":[{"href":"https:\/\/www.dianapps.com\/blog\/wp-json\/wp\/v2\/media?parent=7486"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.dianapps.com\/blog\/wp-json\/wp\/v2\/categories?post=7486"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.dianapps.com\/blog\/wp-json\/wp\/v2\/tags?post=7486"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}