<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by abderrahman turki on Medium]]></title>
        <description><![CDATA[Stories by abderrahman turki on Medium]]></description>
        <link>https://medium.com/@abderrahman.turki?source=rss-df23a55c1b91------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*LlRrNiNslvVUDLVx</url>
            <title>Stories by abderrahman turki on Medium</title>
            <link>https://medium.com/@abderrahman.turki?source=rss-df23a55c1b91------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:53:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abderrahman.turki/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating a Reusable Axios Wrapper for Your React Applications: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@abderrahman.turki/creating-a-reusable-axios-wrapper-for-your-react-applications-a-step-by-step-guide-fe93c963d05?source=rss-df23a55c1b91------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe93c963d05</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[axios-react]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[axios]]></category>
            <dc:creator><![CDATA[abderrahman turki]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 10:56:09 GMT</pubDate>
            <atom:updated>2023-04-06T10:56:09.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eW2dlTZaHi3pX84ltaVIeQ.jpeg" /></figure><p>Introduction:</p><p>In this article, we will discuss the benefits of creating an Axios wrapper for your React applications and guide you through the process of setting up one from scratch. This approach allows you to maintain a consistent API interaction across your application, making it more maintainable and scalable. The article is designed for beginners, so we will provide a step-by-step guide, starting from installing React to sending a request using the custom Axios wrapper.</p><h3>Table of Contents</h3><ol><li>Setting up a new React project</li><li>Installing Axios</li><li>Creating an Axios wrapper</li><li>Benefits of using an Axios wrapper</li><li>Example: Sending a request using the custom Axios wrapper</li><li>Conclusion</li></ol><h3>1. Setting up a new React project</h3><p>First, let’s create a new React project using create-react-app. Open your terminal and run the following command:</p><pre>npx create-react-app axios-wrapper-example</pre><p>Once the project is created, navigate to the project folder:</p><pre>cd axios-wrapper-example</pre><h3>2. Installing Axios</h3><p>Next, install Axios, the HTTP client we will be using, by running:</p><pre>npm install axios</pre><h3>3. Creating an Axios wrapper</h3><ol><li>Create the necessary folder and file: Inside your src folder, create a new folder named services. This folder will hold the Axios wrapper file. Inside the services folder, create a new file named baseHttp.ts. We will use this file to create our Axios wrapper.</li><li>Define the required interfaces: Inside the baseHttp.ts file, start by defining the required interfaces for query parameters and request options. These interfaces will help with type-checking when using the Axios wrapper.</li></ol><pre>export interface Params {<br>  [key: string]:<br>    | boolean<br>    | string<br>    | string[]<br>    | number<br>    | number[]<br>    | {<br>        [key: string]: string[];<br>      }<br>    | undefined;<br>}<br><br>export interface HttpParamsType&lt;T = typeof body&gt; {<br>  queryParams?: Params;<br>  body?: T;<br>}</pre><p>3. Create the Axios instance: Now, create the Axios instance with your desired configuration. In this case, we set the baseURL to the value of the REACT_APP_API_URL environment variable, and enable withCredentials for sending cookies with requests.</p><pre>const instance = axios.create({<br>  baseURL: &#39;your base api url&#39;,<br>});</pre><p>4. Define the request method: Create a generic request method that takes the HTTP method, URL, request options, and an optional cancel token as arguments. This method will be responsible for sending requests using the Axios instance. It will handle errors and return the response data.</p><pre>async function request&lt;T&gt;(method: HttpMethod, url: string, paramsData?: HttpParamsType): Promise&lt;T&gt; {<br>  try {<br>    const { data } = await instance.request&lt;T&gt;({<br>      method,<br>      url,<br>      data: paramsData?.body,<br>      params: paramsData?.queryParams,<br>      headers: {<br>        &#39;content-type&#39;: paramsData?.body instanceof FormData ? &#39;multipart/form-data&#39; : &#39;application/json&#39;,<br>      }<br>    });<br><br>    return data;<br>  } catch (error) {<br>    throw ErrorResponse.mapFromApi(error as ErrorResponseModel);<br>  }<br>}</pre><p>5. Define helper methods: Define the helper methods for making get, post, patch, and delete requests. These methods will utilize the request method to send requests with the appropriate HTTP method.</p><pre>function get&lt;T&gt;(url: string, paramsData?: HttpParamsType): Promise&lt;T&gt; {<br>  return request&lt;T&gt;(HttpMethod.Get, url, paramsData);<br>}<br><br>function post&lt;T&gt;(url: string, paramsData?: HttpParamsType): Promise&lt;T&gt; {<br>  return request&lt;T&gt;(HttpMethod.Post, url, paramsData);<br>}<br><br>function patch&lt;T&gt;(url: string, paramsData?: HttpParamsType): Promise&lt;T&gt; {<br>  return request&lt;T&gt;(HttpMethod.Patch, url, paramsData);<br>}<br><br>function remove&lt;T = void&gt;(url: string, paramsData?: HttpParamsType): Promise&lt;T&gt; {<br>  return request&lt;T&gt;(HttpMethod.Delete, url, paramsData);<br>}</pre><h3>5. Example: Sending a request using the custom Axios wrapper :</h3><p>Now, let’s create a simple example using our custom Axios wrapper. In the src folder, create a new file named App.tsx. Replace its content with the following :</p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br>import { baseHttp } from &#39;./services/baseHttp&#39;;<br><br>function App() {<br>  const [data, setData] = useState(null);<br><br>  useEffect(() =&gt; {<br>    async function fetchData() {<br>      try {<br>        const response = await baseHttp().get(&#39;https://jsonplaceholder.typicode.com/todos/1&#39;);<br>        setData(response);<br>      } catch (error) {<br>        console.error(&#39;Error fetching data:&#39;, error);<br>      }<br>    }<br><br>    fetchData();<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Data from API:&lt;/h1&gt;<br>      {data ? &lt;pre&gt;{JSON.stringify(data, null, 2)}&lt;/pre&gt; : &lt;p&gt;Loading...&lt;/p&gt;}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>In this example, we’re using the custom baseHttp wrapper to send a GET request to the https://jsonplaceholder.typicode.com/todos/1 endpoint. The response is then displayed on the page.</p><h3>4. Benefits of using an Axios wrapper</h3><ul><li>Consistent configuration: The wrapper allows you to maintain a consistent configuration for Axios throughout your application. This includes setting base URLs, authentication headers, and other settings.</li><li>Centralized error handling: With a wrapper, you can centralize error handling, making it easier to handle errors consistently and log or report them as needed.</li><li>Reusable helper methods: The wrapper includes reusable methods for making requests, such as get, post, patch, and delete. These methods make it easy to send requests without repeating code.</li><li>Easier maintenance: By using a wrapper, it’s easier to maintain and update your Axios configuration and helper methods in one place.</li><li>Another great advantage of creating a reusable Axios wrapper is the ability to share it across multiple React projects within a monorepo. Monorepos allow you to manage multiple packages within a single repository, making it easier to share code and dependencies across projects. Yarn Workspaces is a feature built into Yarn that simplifies working with monorepos (We will discuss this in the next article!).</li></ul><h3>Conclusion</h3><p>In this article, we discussed the importance of creating a reusable Axios wrapper for your React applications and provided a step-by-step guide on how to set one up. By using a custom Axios wrapper, you can maintain consistent API interactions across your application, centralize error handling, and make your code more maintainable and scalable.</p><p>We demonstrated how to set up a new React project, install Axios, and create an Axios wrapper with reusable helper methods. We also explained the benefits of using an Axios wrapper and provided an example of sending a request using the custom wrapper.</p><p>By following this guide, you should now have a solid understanding of the benefits and process of creating an Axios wrapper for your React applications. With this knowledge, you can build more efficient and maintainable applications that can scale as your project grows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe93c963d05" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>