<?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 Barisberkemalkoc on Medium]]></title>
        <description><![CDATA[Stories by Barisberkemalkoc on Medium]]></description>
        <link>https://medium.com/@barisberkemalkoc?source=rss-3859b2cf7dac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DFeEdCCk8Yu3Ylk9</url>
            <title>Stories by Barisberkemalkoc on Medium</title>
            <link>https://medium.com/@barisberkemalkoc?source=rss-3859b2cf7dac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 14:42:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@barisberkemalkoc/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[Spirit of React Native -1 (Introduction to React Native and its Architecture)]]></title>
            <link>https://medium.com/@barisberkemalkoc/spirit-of-react-native-1-introduction-to-react-native-and-its-architecture-af811286d70d?source=rss-3859b2cf7dac------2</link>
            <guid isPermaLink="false">https://medium.com/p/af811286d70d</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[hot-reloading]]></category>
            <category><![CDATA[fabric]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Barisberkemalkoc]]></dc:creator>
            <pubDate>Wed, 10 Apr 2024 18:03:16 GMT</pubDate>
            <atom:updated>2024-04-10T18:05:39.267Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VqkW25MowtCtZutj.png" /></figure><p>Hello, I’m Baris. I’ve decided to write a comprehensive Medium series dedicated to unravelling the intricacies and unlocking the full potential of React Native, a revolutionary framework that bridges the gap between the ease of web development and the power of building native mobile apps. I’m going to take this series as far as I can and keep it updated. In this series, we’ll embark on a journey from the core of React Native’s architecture to the final touches of publishing a mobile app, covering every important aspect in between. Not only me but also you will be on this journey. For this, if you specify the details you want me to mention or the details you want to move forward as a comment or question, I will try to address in the next article or continuation of the series. Whether you are an experienced developer or new to the world of mobile application development, this series will push us to take deep dives into React Native’s bridge mechanism, component lifecycle, state management, and beyond, and we will take ourselves one step further with what we learn in these dives. Through a mix of theoretical exploration and practical examples, I’ll immerse you in a comprehensive understanding of how to leverage React Native for efficient, performant, and visually appealing mobile apps. From mastering style and layout to optimising performance and navigating the publishing process, I’ll strive to create a series you’ll want to keep by your bedside as I demystify the complexities of React Native and turn you into a proficient mobile app developer. Let’s dive into the vibrant world of React Native and uncover all the possibilities it offers for mobile app development. Remember that neither I nor you will determine the course of this series. The course of this series depends entirely on the spirit of React Native and the wind. At the beginning of the series, I want to say something for beginners: “It’s not rocket science”.</p><p>While entering the world of mobile app development brings with it a myriad of technologies and frameworks, React Native stands out as a leading choice for developers looking to blend the performance of native apps with the flexibility and speed of web development. At the heart of React Native is a unique architecture that enables this seamless integration, facilitating a common codebase across iOS and Android while maintaining high performance and user experience. In this article, we will explore how React Native layers its architecture to harmonise JavaScript and native platform capabilities to revolutionise the development process. We’ll examine the core components of React Native, including the bridge, master, and JavaScript threads, and how they work together to bring responsive and visually appealing mobile apps to life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/0*wj7Ofpuld9hRWpf5.jpg" /></figure><p><strong>The topics you can find in this article :</strong></p><ul><li><strong>What is React Native?</strong></li><li><strong>The Birth and Evolution of React Native</strong></li><li>Hot Reloading 🔥</li><li>Support for Android 🤖</li><li>Fabric and TurboModules 🚀</li><li>Hermes Engine ⚙️</li></ul><h3>What is React Native?</h3><ul><li>React Native is an open source mobile application framework <strong>created by Facebook</strong> and currently maintained <strong>by Meta </strong>and the developer community, <strong>namely us</strong>. It is designed to enable developers to use React, a popular JavaScript library, to build native platform features as well as user interfaces to develop mobile apps for iOS and Android from a single JavaScript code base. This approach enables the development of apps that run on multiple platforms with a look, feel and performance that is virtually indistinguishable from native apps developed using <strong>Swift or Objective-C</strong> for iOS and <strong>Java or Kotlin</strong> for Android.</li><li>One of the key features of React Native is its ability to translate JavaScript-written application logic and user interfaces into native platform-specific components. This means that a button in React Native, for example, renders as a genuine <strong>UIButton on iOS</strong> or an <strong>android.widget.Button on Android</strong>, ensuring that users experience the same performance and visual consistency they would expect from a <strong>native app.</strong></li><li>React Native’s architecture is built around the principle of <a href="https://reactnative.dev/">‘<strong>Learn once, write anywhere.</strong>’</a> While it enables code reuse across platforms, it also offers the flexibility to incorporate native code when needed. This hybrid approach optimizes development efficiency without sacrificing the app’s quality or user experience.</li><li>Moreover, React Native comes with a <strong>rich ecosystem</strong>, including a vast library of <strong>pre-made</strong> components, tools for debugging and performance optimization, and a <a href="https://reactnative.dev/community/communities"><strong>strong community</strong></a><strong> </strong>support network. This ecosystem not only accelerates the development process but also makes it easier for developers to maintain and update their apps.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GKMbAGBqnVDbOvg1.png" /></figure><h3>The Birth and Evolution of React Native</h3><p><em>(Discuss the history of React Native, its inception, major updates, and how it has evolved over time)</em></p><ul><li>The journey of React Native began as an internal hackathon project at Facebook in 2013, born out of the need for a more efficient and unified way of developing mobile applications. Facebook was seeking a solution that would combine the advantages of web development — such as quick iterations and a single codebase — with the performance and user experience of native mobile apps. In 2015, React Native was officially released to the public, opening up a new frontier in mobile development that allowed for cross-platform apps built using only JavaScript.</li><li>Although react is not native as direlkt, you should take a look at this documentary <a href="https://www.youtube.com/watch?v=8pDqJVdNa44&amp;t=4200s&amp;ab_channel=Honeypot">“How A Small Team of Developers Created React at Facebook”</a> to understand the Facebook mentality and see how those days came.</li></ul><h4><strong>Hot Reloading </strong>🔥</h4><ul><li>The introduction of the Hot Reloading feature in React Native was a significant milestone that fundamentally transformed the mobile app development process. Before Hot Reloading, developers faced a tedious cycle of making changes in the code, rebuilding the entire app, and then relaunching it on a simulator or device to see the effects of those changes. This process was not only time-consuming but also disruptive to the development workflow, especially for minor tweaks and adjustments.</li><li>The essence of Hot Reloading lies in its ability to maintain the app’s state even after the code has changed. This means that if a developer modifies the UI or the logic of a component, they can see the changes take effect in real time, without losing the current state of the app. For example, if a developer is working on a form inside the app and decides to adjust the layout or styling of a text input, Hot Reloading updates the UI on the fly without resetting the form, preserving any text or selections the developer has made.</li><li><strong>Moreover,</strong> Hot Reloading makes the development process more engaging and enjoyable, as developers can immediately see the outcome of their creative endeavors.</li><li><strong>However,</strong> it’s important to note that while Hot Reloading is a powerful tool, it’s not a one-size-fits-all solution. There are scenarios, particularly those involving changes to the app’s native code or the overall app structure, where a full rebuild and relaunch are necessary. Nevertheless, for the vast majority of development tasks centered around JavaScript and React components, Hot Reloading stands out as an invaluable feature.</li></ul><h4>Support for Android 🤖</h4><p><em>(While initially iOS-focused, React Native quickly added support for Android, fulfilling its promise of truly cross-platform development.)</em></p><ul><li>The expansion of React Native to include support for Android was a significant moment in the framework’s transition from an iOS-centric tool to a truly cross-platform solution. Initially launched with a focus on iOS, React Native’s potential to facilitate mobile app development on both major mobile platforms was quickly realised, and the move to embrace Android enabled a transition to a broader vision that allows developers to build universal apps using a single codebase without sacrificing the performance and user experience that native apps are known for.</li><li>The introduction of Android support involved extending React Native’s core architecture — its bridge, components, and APIs — to interact seamlessly with Android’s native components and lifecycle. This development was not trivial, as it required addressing the nuanced differences between iOS and Android, including navigation patterns, design elements, and system behaviors. By abstracting these platform-specific details behind a unified JavaScript API, React Native empowered developers to write platform-agnostic code that could adapt to each environment intelligently.</li><li>The support for Android has significantly broadened the impact and appeal of React Native.</li><li><strong>In conclusion,</strong> the introduction of Android support in React Native was a watershed moment that transformed the framework into a versatile and indispensable tool for mobile developers. By enabling truly cross-platform development, React Native has played a pivotal role in shaping the mobile landscape, fostering a more integrated and efficient approach to app creation.</li></ul><h4>Fabric and TurboModules 🚀</h4><ul><li>The announcement of Fabric and TurboModules marked a pivotal moment in the evolution of React Native, signifying a major stride towards optimizing its core architecture for better performance and efficiency. This initiative, often referred to as the “React Native re-architecture,” represents a comprehensive effort to address some of the long-standing limitations of the framework, particularly around the bridge — the crucial component that facilitates communication between the JavaScript and native realms of a React Native application.</li><li><strong>The bridge in React Native</strong> has historically been responsible for serializing, sending, and receiving messages between the JavaScript world and native code. This process involves turning complex objects into strings (serialization) that can be sent over the bridge, and then parsing them back into their original form on the other side. While effective in enabling <strong>cross-language</strong> communication, this serialization process can be a bottleneck, impacting the performance of React Native apps, <strong>especially in areas requiring frequent interaction between JavaScript and native code</strong>.</li><li><a href="https://reactnative.dev/architecture/fabric-renderer"><strong>Fabric</strong></a> is a <strong>new UI layer for React Native</strong> that replaces the existing bridge with a more direct and efficient system for handling UI operations. It utilizes a concept called “JSI” (JavaScript Interface), which allows <strong>JavaScript to directly call into native code</strong> without the need for serialization. This means UI updates and interactions can happen more <strong>quickly and smoothly,</strong> enhancing the responsiveness of React Native apps.</li><li><a href="https://github.com/reactwg/react-native-new-architecture/blob/main/docs/turbo-modules.md"><strong>TurboModules</strong></a> reimagines the way <strong>native modules work in React Native.</strong> Like<strong> Fabric</strong>, TurboModules also leverage <strong>JSI</strong> to enable direct access to native functions from JavaScript. This eliminates the need for the bridge and serialization process for accessing native modules, significantly reducing the overhead and improving the performance of operations that rely on native code. <strong>TurboModules also allow for lazy loading of native modules</strong>, meaning they are only initialized when needed, <strong>further optimizing resource usage and startup time.</strong></li><li><strong>The introduction of Fabric and TurboModules represents a significant technological leap for React Native</strong>. By streamlining the interaction between JavaScript and native code, these updates aim to make React Native apps as performant as their native counterparts, if not more so. For developers, this means faster iteration times, <strong>reduced complexity in bridging custom native code</strong>, and ultimately, the ability to create <strong>smoother and more responsive applications</strong>.</li><li><strong>In conclusion</strong>, Fabric and TurboModules are not just updates; they are transformative changes that pave the way for the next generation of React Native applications. They embody the framework’s evolution towards a <strong>more efficient and performant future, promising an exciting horizon for developers and users alike.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*QTo8Lbj4bm8FUxXH" /></figure><h4>Hermes Engine ⚙️</h4><p><em>(Facebook introduced Hermes, an open-source JavaScript engine optimized for React Native, to improve app performance, especially on Android. Hermes helps in reducing app size, memory usage, and startup time)</em></p><ul><li>Hermes is a lightweight JavaScript engine optimized for running React Native applications. It was designed from the ground up with the goal of improving the performance of React Native apps on mobile devices, where resources are more limited compared to desktop environments. By focusing on compilation strategies and runtime optimizations that specifically benefit mobile app use cases, Hermes significantly enhances the user experience of React Native apps.</li><li><strong>Hermes achieves faster startup times </strong>by pre-compiling JavaScript into bytecode. This means that the JavaScript code of a React Native app is compiled during the <strong>build process, not at runtime</strong>. As a result, the app can launch and <strong>become interactive more quickly,</strong> which is crucial for maintaining user engagement.</li><li><strong>Hermes is designed to be memory-efficient</strong>, a critical factor for mobile devices with<strong> limited RAM</strong>. By optimizing <strong>garbage collection</strong> and reducing the <strong>memory footprint of JavaScript execution</strong>, Hermes ensures that React Native apps <strong>run smoothly, even on devices with less memory.</strong></li><li><strong>The bytecode generated by Hermes is compact</strong>, leading to <strong>smaller app</strong> sizes. This is making React Native apps more accessible.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ygY0sLV2Mcrb4I1X.png" /></figure><p><strong>In the continuation of the series</strong>, we will continue with the main title “Introduction to React Native and its Architecture”. The topics I plan to touch on will be “Main Thread, JS Thread and Bridges” under the title “Understanding the Core of React Native Architecture” You can specify the topics you want to see next to these titles. 👋👋👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af811286d70d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Communication with React Native (What is Socket ?)]]></title>
            <link>https://medium.com/@barisberkemalkoc/real-time-communication-with-react-native-what-is-socket-415b452875bc?source=rss-3859b2cf7dac------2</link>
            <guid isPermaLink="false">https://medium.com/p/415b452875bc</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Barisberkemalkoc]]></dc:creator>
            <pubDate>Fri, 15 Dec 2023 13:17:25 GMT</pubDate>
            <atom:updated>2023-12-15T13:17:25.033Z</atom:updated>
            <content:encoded><![CDATA[<h3>Real-Time Communication with React Native (What is Socket ?)</h3><h4>What is Socket ?</h4><p>Socket is a communication interface that allows communication between devices on computer networks and the Internet. Socket allows a program to exchange data with other programs over the network. Socket communication is usually performed using communication protocols such as TCP (Transmission Control Protocol) or UDP (User Datagram Protocol).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*TIVbsd5wIqg4taVvhRCWGA.jpeg" /><figcaption>What is Socket ?</figcaption></figure><p>Basically, a socket provides a connection between two ends. This connection allows one device to send data to or receive data from another device via a specific IP address and port number. Socket programming is often used to enable a device to communicate with other devices on the network.</p><p><em>Server : The server listens and accepts incoming connections via a specific IP address and port number. The server provides a service that usually serves clients.</em></p><p><em>Client : The client establishes a connection to a specific server IP address and port number. The client uses a specific service, usually by connecting to a server.</em></p><p>Socket programming is supported in many programming languages and provides developers with a powerful set of tools for communicating data over a network. The use of sockets is common for inter-application data exchange, file transfer, real-time communication and other network-based application scenarios.</p><h4>What Are Socket Types ?</h4><blockquote>Stream Sockets :</blockquote><ul><li>TCP (Transmission Control Protocol) : TCP-based sockets ensure reliable and sequential data transmission. The data reaches the receiver completely and sequentially.</li><li>UNIX Sockets : Used for inter-process communication in UNIX-based operating systems.</li></ul><blockquote>Datagram Sockets :</blockquote><ul><li>UDP (User Datagram Protocol) : UDP-based sockets provide unreliable and unordered data transmission. Data can go from source to destination, but there is no guarantee of ordering.</li></ul><blockquote>Raw Sockets :</blockquote><ul><li>Raw Sockets: Raw sockets provide direct control over low-level network packets. It is often used to examine network protocols, create packets, or implement custom network applications.</li></ul><blockquote>Sequential Packet Sockets :</blockquote><ul><li>SEQPACKET Sockets : In UNIX-based operating systems, sequential packet sockets support reliable and unordered data transmission. This is a type of protocol in which data is transmitted in a specific order.</li></ul><blockquote>Reliable Datagram Sockets :</blockquote><ul><li>RDS (Reliable Datagram Sockets): Supports reliable, sequential communication between two points. This is a type of socket designed specifically for InfiniBand networks.</li></ul><h4>How does Socket work? (Let’s take a brief look)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*zGLHWk42JlwkGXMLiqad0A.png" /><figcaption>How does Socket work?</figcaption></figure><ul><li><strong>Connection Establishment </strong>: A connection must be established between the devices to be communicated with. This is usually done by connecting one device to another device via a specific IP address and port number.</li><li><strong>Socket Creation</strong> : A socket is created on both devices to be communicated with. This socket can be considered as one end of the connection. On the server side there is usually a listening socket and on the client side a connection socket.</li><li><strong>Data Transmission : </strong>Once the connection is established, data transmission begins. The exchange of data between the two parties takes place via a socket. The sending party sends data to a specific IP address and port number via the socket, and the receiving party reads this data.</li><li><strong>Transmission Control :</strong> During data transmission, the transmission is controlled depending on the protocol used. For example, the TCP protocol has various mechanisms to ensure reliable and sequential data transmission. Through these mechanisms, situations such as packet loss and out of sequence are controlled.</li><li><strong>Connection Termination :</strong> When communication is complete or when a device wants to terminate the connection, the connection is terminated. This is usually done with a termination handshake.</li><li><strong>Error Handling : </strong>Error control mechanisms are used for errors and problems that may occur during socket communication. Errors should generally be handled appropriately in client and server applications.</li></ul><h4>How to Use ?</h4><p>I will explain how both server and client side will work with a simple example.</p><p>Firstly, create a simple Node.js application to start a socket.io server.</p><pre>// server.js<br>const http = require(&#39;http&#39;);<br>const express = require(&#39;express&#39;);<br>const { Server } = require(&#39;socket.io&#39;);<br><br>const app = express();<br>const server = http.createServer(app);<br>const io = new Server(server);<br><br>io.on(&#39;connection&#39;, (socket) =&gt; {<br>  console.log(&#39;A user is connected&#39;);<br><br>  socket.on(&#39;message&#39;, (msg) =&gt; {<br>    io.emit(&#39;message&#39;, msg);<br>  });<br><br>  socket.on(&#39;disconnect&#39;, () =&gt; {<br>    console.log(&#39;One user left&#39;);<br>  });<br>});<br><br>const PORT = 3000;<br>server.listen(PORT, () =&gt; {<br>  console.log(`Server running on port ${{PORT}`);<br>});</pre><p>To start the server application, use the following command in the terminal:</p><pre>node server.js</pre><p>Let’s create a chat screen in the React Native application and communicate with the server using Socket.io on this screen.</p><pre>// App.js<br>import React, { useState, useEffect } from &#39;react&#39;;<br>import { View, Text, TextInput, Button, ScrollView } from &#39;react-native&#39;;<br>import io from &#39;socket.io-client&#39;;<br><br>const socket = io(&#39;http://barisberkemalkoc:3000&#39;); // Server address<br><br>export default function App() {<br>  const [message, setMessage] = useState(&#39;&#39;);<br>  const [messages, setMessages] = useState([]);<br><br>  useEffect(() =&gt; {<br>    // Listen to messages from the server<br>    socket.on(&#39;message&#39;, (msg) =&gt; {<br>      setMessages([...messages, msg]);<br>    });<br><br>    return () =&gt; {<br>      socket.disconnect(); // Close socket connection when component unmount<br>    };<br>  }, [messages]);<br><br>  const sendMessage = () =&gt; {<br>    // Sending a message<br>    if (message.trim() !== &#39;&#39;) {<br>      socket.emit(&#39;message&#39;, message);<br>      setMessage(&#39;&#39;);<br>    }<br>  };<br><br>  return (<br>    &lt;View style={{ flex: 1, justifyContent: &#39;center&#39;, padding: 16 }}&gt;<br>      &lt;ScrollView style={{ flex: 1, marginBottom: 16 }}&gt;<br>        {messages.map((msg, index) =&gt; (<br>          &lt;Text key={index}&gt;{msg}&lt;/Text&gt;<br>        ))}<br>      &lt;/ScrollView&gt;<br>      &lt;View style={{ flexDirection: &#39;row&#39;, alignItems: &#39;center&#39; }}&gt;<br>        &lt;TextInput<br>          style={{ flex: 1, height: 40, borderColor: &#39;gray&#39;, borderWidth: 1, marginRight: 8 }}<br>          onChangeText={(text) =&gt; setMessage(text)}<br>          value={message}<br>        /&gt;<br>        &lt;Button title=&quot;Send&quot; onPress={sendMessage} /&gt;<br>      &lt;/View&gt;<br>    &lt;/View&gt;<br>  );<br>}</pre><p>In this example, we made a chat application with React Native. Users can send messages to each other, and the messages sent are instantly forwarded to all users. A simple chat application was created using Socket.io events such as ‘connection’, ‘message’, and ‘disconnect’.</p><p>Now let’s make an example using Laravel instead of Node.js on the server side in a little more detail.</p><p>Firstly, let’s create our client-side socket controller with our socket.ts file</p><pre>//socket.ts<br>import Echo from &#39;laravel-echo&#39;;<br>import io from &#39;socket.io-client&#39;;<br><br>const echo = new Echo({<br>  host: &#39;https://barisberkemalkoc.com&#39;,<br>  broadcaster: &#39;socket.io&#39;,<br>  client: io,<br>});<br><br>export default echo;</pre><p>Defining your socket events as constant will both increase your code quality and provide you convenience.</p><pre>export const SocketEvent = {<br>  MESSAGE_SENT: &#39;.MessageSent&#39;,<br>  RECEIVED_MESSAGE: &#39;.ReceivedMessage&#39;,<br>};</pre><p>Now let’s take another look at our example using these.</p><pre>// App.js<br>import React, { useState, useEffect } from &#39;react&#39;;<br>import { View, Text, TextInput, Button, ScrollView } from &#39;react-native&#39;;<br>import io from &#39;socket.io-client&#39;;<br><br>const socket = io(&#39;http://barisberkemalkoc:3000&#39;); // Server address<br><br>export default function App({userDetail}) {<br>  const [message, setMessage] = useState(&#39;&#39;);<br>  const [messages, setMessages] = useState([]);<br><br>  useEffect(() =&gt; {<br>    echo<br>      .channel(`staging-chat-channel-${userDetail.channelId}`)<br>      .listen(SocketEvent.MESSAGE_SENT, (response: any) =&gt; {<br>        setMessages(response.message);<br>      });<br><br>    return () =&gt; {<br>      echo<br>        .channel(`staging-chat-channel-${userDetail.channelId}`)<br>        .stopListening(SocketEvent.MESSAGE_SENT);<br>    };<br>  }, [isFocused]);<br><br> <br>const handleMessageSend = () =&gt; {<br>    chatServices.sendMessageWithChannelId(message, userDetail.channelId);<br>  };<br><br>  return (<br>    &lt;View style={{ flex: 1, justifyContent: &#39;center&#39;, padding: 16 }}&gt;<br>      &lt;ScrollView style={{ flex: 1, marginBottom: 16 }}&gt;<br>        {messages.map((msg, index) =&gt; (<br>          &lt;Text key={index}&gt;{msg}&lt;/Text&gt;<br>        ))}<br>      &lt;/ScrollView&gt;<br>      &lt;View style={{ flexDirection: &#39;row&#39;, alignItems: &#39;center&#39; }}&gt;<br>        &lt;TextInput<br>          style={{ flex: 1, height: 40, borderColor: &#39;gray&#39;, borderWidth: 1, marginRight: 8 }}<br>          onChangeText={(text) =&gt; setMessage(text)}<br>          value={message}<br>        /&gt;<br>        &lt;Button title=&quot;Send&quot; onPress={handleMessageSend} /&gt;<br>      &lt;/View&gt;<br>    &lt;/View&gt;<br>  );<br>}</pre><p>In this code snippet, we transmit the message to the backend with the service. Backend triggers the socket with channelId and transmits the message we send to the other side.</p><pre>//1 <br>useEffect(() =&gt; {<br>    //2<br>    echo<br>      .channel(`staging-chat-channel-${userDetail.channelId}`)<br>       //3<br>      .listen(SocketEvent.MESSAGE_SENT, (response: any) =&gt; {<br>        //4<br>        setMessages(response.message);<br>      });<br>    //5<br>    return () =&gt; {<br>      echo<br>        .channel(`staging-chat-channel-${userDetail.channelId}`)<br>        .stopListening(SocketEvent.MESSAGE_SENT);<br>    };<br>  }, [isFocused]);</pre><p>Now let’s examine the details of the code:</p><ul><li>(//1) The useEffect hook is triggered when the component is mounted or updated (re-rendered). This useEffect fires if the isFocused variable specified in the dependency array changes or if the component is rendered for the first time.</li><li>(//2) echo.channel(…) connects to an Echo channel. The name of this channel contains the value userDetail.channelId. That is, it connects to a channel starting with staging-chat-channel- and ending with userDetail.channelId.</li><li>(//3) .listen(SocketEvent.MESSAGE_SENT, (response: any) =&gt; {…}) to listen for a specific event. This event is represented by a constant named SocketEvent.MESSAGE_SENT. When this event occurs, the provided callback function is executed and called with the value response.message.</li><li>(//4) setMessages(response.message) updates the local state of the component. This state update ensures that the component is rendered again when a new message arrives, so that new messages are shown to the user.</li><li>(//5) In return () =&gt; {…}, the useEffect hook performs cleanup operations in case the component is updated. In this case, the listening process connected to the Echo channel is switched off and no longer reacts to this event.</li></ul><p><strong>Thanks for reading — BBM</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=415b452875bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native MMKV Library]]></title>
            <link>https://medium.com/@barisberkemalkoc/react-native-mmkv-library-fcc11a0b7628?source=rss-3859b2cf7dac------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcc11a0b7628</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Barisberkemalkoc]]></dc:creator>
            <pubDate>Sun, 10 Dec 2023 18:56:32 GMT</pubDate>
            <atom:updated>2023-12-10T18:59:28.066Z</atom:updated>
            <content:encoded><![CDATA[<h4>An Extraordinary Data Storage Solution for Speed and Security</h4><p>In this article, we will discuss what MMKV is and how to use it (in React Native), examples and details of the best ways to use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2IxFOAlmFfcFDegN6UVP2w.png" /><figcaption>What is the MMKV ?</figcaption></figure><p>“Storage” refers to an area where information is temporarily or permanently stored. Within an application, storage is used to store various data and access it later. In React Native or other mobile application development frameworks, these storage areas are usually located in the local memory of the device. There are two basic types:</p><h4>Temporary Storage:</h4><ul><li>It is the area where data temporarily used by the application is stored.</li><li>For example, temporary information (e.g. session state) about the user during a session of the application can be stored here.</li><li>Such storage is usually cleared when the application is closed or the device is restarted.</li></ul><h4>Permanent Storage:</h4><ul><li>It is the area that is used by the application on an ongoing basis or where permanent information is stored, such as storing the user’s preferences.</li><li>For example, user preferences, application settings or various data can be stored in this area.</li><li>This type of storage is a space where data is preserved even when the application is closed or the device is restarted.</li></ul><h4>In React Native, Storage Solutions</h4><blockquote>1- AsyncStorage:</blockquote><ul><li>It is an API offered by React Native.</li><li>It works asynchronously and is often used to store small pieces of data.</li><li>This storage type is usually used to store key-value pairs.</li></ul><blockquote>2- React Native SQLite:</blockquote><ul><li>It is used for more complex data structures using SQLite database.</li><li>Suitable for advanced database operations and larger data sets.</li></ul><blockquote>3- MMKV:</blockquote><ul><li>It is a C++ library developed by WeChat.</li><li>It is particularly performance orientated and provides fast data storage with a small footprint.</li></ul><p>Each storage solution is selected according to specific scenarios or performance expectations. For example, AsyncStorage may be suitable for small pieces of data, while solutions such as SQLite or MMKV may be more suitable for large and complex data sets.</p><h3>What is MMKV and why should you use it?</h3><h4>Main features of the MMKV</h4><ul><li>Fast and Efficient : MMKV is designed to work quickly. It is especially optimised for mobile applications and operates with low latency.</li><li>Cross Platform Support : MMKV can be used on different mobile platforms such as Android and iOS. This allows developers to manage their applications consistently across different platforms and share data.</li><li>Multi-Process Support : MMKV supports multi-process. This allows you to access the same data from multiple locations at the same time. This feature is useful in various scenarios, especially in large and complex applications.</li><li>Thread Safety : MMKV is designed to be used securely in multi-threading environments. This makes it easy for developers to provide concurrent access to data.</li><li>Stackable Data Types : MMKV offers basically “key-value” storage, but supports a wide variety of data types as values. This allows you to store different data types such as text, number, array, object.</li><li>Low Memory Usage : MMKV is characterised by low memory usage. This feature can help your applications manage memory resources more effectively.</li><li>Encryption Support : MMKV offers an option to encrypt your data. This ensures that sensitive information is stored securely.</li><li>Lightweight and Simple API : MMKV is easy to use with a lightweight and simple API. It offers developers a clean interface that they can use to simplify data storage and retrieval processes.</li></ul><h4>Comparison with other data storage methods</h4><ul><li>SharedPreferences : It is faster than SharedPreferences. It provides performance advantage especially in large data sets. SharedPreferences only supports basic data types, while MMKV supports various data types.</li><li>SQLite Database : It is faster than SQLite, especially suitable for small data sets and simple data structures. SQLite allows for more complex data structures and queries because it is a relational database. However, this can also come at the cost of performance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cogXsGnh5RJdWPqPbgDSg.png" /><figcaption>Comparison with other data storage</figcaption></figure><h4>Installing MMKV</h4><p>Before diving into the world of MMKV, it is very important to have MMKV installed in your project. If you haven’t added MMKV to your project yet, don’t worry — the process is simple.</p><p>Using yarn :</p><pre>yarn add react-native-mmkv<br>cd ios &amp;&amp; pod install</pre><p>or using expo :</p><pre>npx expo install react-native-mmkv<br>npx expo prebuild</pre><h4>MMKV Configuration</h4><p>Before using MMKV in your project, you usually need to configure it once when the application is started. In your React Native project, you can usually make this configuration in your index.js/ or App.js or mmkv.js/ts file.</p><pre>import { AppRegistry } from &#39;react-native&#39;;<br>import App from &#39;./App&#39;;<br>import { name as appName } from &#39;./app.json&#39;;<br>import { MMKV } from &#39;react-native-mmkv&#39;<br><br>// Create and initialise the MMKV instance<br>export const storage = new MMKV();<br><br>// Start the application<br>AppRegistry.registerComponent(appName, () =&gt; App);</pre><p>or (with customize)</p><pre>import { MMKV } from &#39;react-native-mmkv&#39;<br><br>export const storage = new MMKV({<br>  id: `user-${userId}-storage`,<br>  path: `${USER_DIRECTORY}/storage`,<br>  encryptionKey: &#39;hunter2&#39;<br>})</pre><p>This creates a new storage instance using a custom MMKV storage ID. By using a custom storage ID, your storage is separated from the default MMKV storage of your app.</p><ul><li>id: ID of the MMKV instance. Use different ids if you want to use more than one instance. For example, you can separate the storage of the public application from the storage of a logged in user (required if the path or encryptionKey fields are specified, otherwise ‘mmkv.default’ by default)</li><li>path: The MMKV instance’s root path. By default, MMKV stores file inside $(Documents)/mmkv/. You can customize MMKV’s root directory on MMKV initialization.</li><li>encryptionKey : encryptionKeyThe MMKV instance&#39;s encryption/decryption key. By default, MMKV stores all key-values in plain text on file, relying on iOS&#39;s/Android&#39;s sandbox to make sure the file is encrypted. Should you worry about information leaking, you can choose to encrypt MMKV.</li></ul><h4>Set</h4><pre>storage.set(&#39;user.name&#39;, &#39;Marc&#39;)<br>storage.set(&#39;user.age&#39;, 21)<br>storage.set(&#39;is-mmkv-fast-asf&#39;, true)</pre><h4>Get</h4><pre>const username = storage.getString(&#39;user.name&#39;) // &#39;Marc&#39;<br>const age = storage.getNumber(&#39;user.age&#39;) // 21<br>const isMmkvFastAsf = storage.getBoolean(&#39;is-mmkv-fast-asf&#39;) // true</pre><h4>Keys</h4><pre>// checking if a specific key exists<br>const hasUsername = storage.contains(&#39;user.name&#39;)<br><br>// getting all keys<br>const keys = storage.getAllKeys() // [&#39;user.name&#39;, &#39;user.age&#39;, &#39;is-mmkv-fast-asf&#39;]<br><br>// delete a specific key + value<br>storage.delete(&#39;user.name&#39;)<br><br>// delete all keys<br>storage.clearAll()</pre><h4>Objects</h4><pre>const user = {<br>  username: &#39;Marc&#39;,<br>  age: 21<br>}<br><br>// Serialize the object into a JSON string<br>storage.set(&#39;user&#39;, JSON.stringify(user))<br><br>// Deserialize the JSON string into an object<br>const jsonUser = storage.getString(&#39;user&#39;) // { &#39;username&#39;: &#39;Marc&#39;, &#39;age&#39;: 21 }<br>const userObject = JSON.parse(jsonUser)</pre><h4>Encryption</h4><pre>// encrypt all data with a private key<br>storage.recrypt(&#39;hunter2&#39;)<br><br>// remove encryption<br>storage.recrypt(undefined)</pre><h4>Buffers</h4><pre>storage.set(&#39;someToken&#39;, new Uint8Array([1, 100, 255]))<br>const buffer = storage.getBuffer(&#39;someToken&#39;)<br>console.log(buffer) // [1, 100, 255]</pre><p>Finally : MMKV is an open-source key-value storage library that appeals to developers looking for fast and efficient data storage solutions, especially in mobile application development. Thanks to its performance advantages, cross-platform support, multi-process support and lightweight design, MMKV is widely preferred in Android and iOS applications. It provides developers with a simple API to store a variety of data types while optimising memory usage. MMKV’s reliable and fast performance provides an important advantage for those who want to improve their mobile application development processes.</p><p><strong>Thanks for reading — BBM</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcc11a0b7628" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Axios Interceptor — Intelligent]]></title>
            <link>https://medium.com/@barisberkemalkoc/axios-interceptor-intelligent-db46653b7303?source=rss-3859b2cf7dac------2</link>
            <guid isPermaLink="false">https://medium.com/p/db46653b7303</guid>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[axios-interceptor]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[request]]></category>
            <dc:creator><![CDATA[Barisberkemalkoc]]></dc:creator>
            <pubDate>Sun, 06 Aug 2023 19:18:55 GMT</pubDate>
            <atom:updated>2023-08-06T19:18:55.133Z</atom:updated>
            <content:encoded><![CDATA[<h3>Axios Interceptor</h3><h3>Intelligent API requests</h3><p>In this article, we will discuss how you can make your API requests faster and more convenient with <em>Axios Interceptor</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4CmiOUvaKN4QlbqbA67sA.png" /><figcaption>Where is the interceptor ?</figcaption></figure><p>Web applications predominantly rely on APIs for data exchange, and in this realm, Axios emerges as an uncomplicated yet powerful HTTP client library. Nevertheless, grappling with prevalent challenges like session management, error handling, and security concerns during API requests can be formidable. This is precisely where the prowess of Axios interceptors becomes evident. In this article, we embark on an insightful journey to decipher the essence of Axios interceptors — uncovering their nature, mastering their usage, and appreciating their utility.</p><p>Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.</p><p><strong>Axios Features</strong></p><ul><li>Make <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequests</a> from the browser</li><li>Make <a href="http://nodejs.org/api/http.html">http</a> requests from node.js</li><li>Supports the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> API</li><li>Intercept request and response</li><li>Transform request and response data</li><li>Cancel requests</li><li>Timeouts</li><li>Query parameters serialization with support for nested entries</li><li>Automatic request body serialization to:</li><li>JSON (application/json)</li><li>Multipart / FormData (multipart/form-data)</li><li>URL encoded form (application/x-www-form-urlencoded)</li><li>Posting HTML forms as JSON</li><li>Automatic JSON data handling in response</li><li>Progress capturing for browsers and node.js with extra info (speed rate, remaining time)</li><li>Setting bandwidth limits for node.js</li><li>Compatible with spec-compliant FormData and Blob (including node.js)</li><li>Client side support for protecting against <a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery">XSRF</a></li></ul><p><strong>Installing Axios</strong></p><p>Before we dive into the world of Axios interceptors, it’s essential to have Axios installed in your project. If you haven’t added Axios to your project yet, worry not — the process is straightforward.</p><p>Using npm:</p><pre>npm install axios</pre><p>or using yarn :</p><pre>yarn add axios</pre><p>Remember, Axios provides a seamless way to interact with APIs, making the integration of interceptors even more potent. With Axios securely in place, we’re now ready to explore the world of interceptors and enhance the capabilities of our API requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ml_FWnUbGkcwT8QJsNxdqg.png" /><figcaption>What is the Axios ?</figcaption></figure><p><strong>Making API Requests with Axios</strong></p><p>Axios excels at simplifying the process of making API requests. With just a few lines of code, you can initiate HTTP GET, POST, PUT, or DELETE requests. Let’s take a look at a basic example:</p><p><em>Getting Data With Get Request</em></p><pre>import axios from &#39;axios&#39;;<br><br>// Making a GET request<br>axios.get(&#39;https://api.bbm.com/posts&#39;)<br>  .then(response =&gt; {<br>    // Handle the successful response<br>    console.log(response.data);<br>  })<br>  .catch(error =&gt; {<br>    // Handle errors<br>    console.error(&#39;An error occurred:&#39;, error);<br>  });</pre><p>In this example, we import Axios and use the axios.get method to retrieve data from the specified URL. The then block handles the successful response, while the catch block deals with any errors that might occur during the request.</p><pre>// Making a GET request with query parameters<br>axios.get(&#39;https://api.bbm.com/posts&#39;, {<br>  params: {<br>    category: &#39;Oppenheimer&#39;,<br>    limit: 42<br>  }<br>})<br>  .then(response =&gt; {<br>    console.log(response.data);<br>  })<br>  .catch(error =&gt; {<br>    console.error(error);<br>  });</pre><p>Often, you’ll need to include query parameters in your API requests.Here, the params object is used to attach query parameters to the URL, enhancing the precision of your API requests.</p><p><em>Sending Data with POST Requests</em></p><p>When sending data, especially for creating or updating resources, you’ll use HTTP POST or PUT requests.</p><pre>// Making a POST request with data<br>const newData = {<br>  title: &#39;Oohs Nolan!&#39;,<br>  content: &#39;Oppenheimer was one of the best cinematographic films<br>           I have ever seen.&#39;<br>};<br><br>axios.post(&#39;https://api.bbm.com/posts&#39;, newData)<br>  .then(response =&gt; {<br>    console.log(response.data);<br>  })<br>  .catch(error =&gt; {<br>    console.error(error);<br>  });</pre><p>In this case, Axios’s axios.post method is employed to send the newData object to the server, creating a new post.</p><p><em>Configuring Request Headers</em></p><pre>// Making a GET request with custom headers<br>const config = {<br>  headers: {<br>    Authorization: &#39;Bearer ACCESS_TOKEN&#39;<br>  }<br>};<br><br>axios.get(&#39;https://api.example.com/protected-resource&#39;, config)<br>  .then(response =&gt; {<br>    console.log(response.data);<br>  })<br>  .catch(error =&gt; {<br>    console.error(error);<br>  });</pre><p>Request headers are essential for various purposes, such as authorization or content negotiation.By setting the headers property in the config object, you can include custom headers in your requests.</p><p><em>Concurrent Requests</em></p><pre>const requestForPosts = axios.get(&#39;https://api.bbm.com/posts&#39;);<br>const requestForTitles = axios.get(&#39;https://api.bbm.com/titles&#39;);<br><br>axios.all([requestForposts, requestForTitles])<br>  .then(axios.spread((responseForPosts, responseForTitles) =&gt; {<br>    console.log(&#39;Response from request for posts:&#39;, responseForPosts.data);<br>    console.log(&#39;Response from request for titles:&#39;, responseForTitles.data);<br>  }))<br>  .catch(error =&gt; {<br>    console.error(error);<br>  });</pre><p>Axios enables you to perform multiple requests concurrently and handle their results using axios.all</p><h3>How can we make the Axios methods I’ve shown more useful?</h3><p>Imagine having a personal assistant who anticipates your needs, streamlines your tasks, and enhances your interactions — that’s precisely what Axios Interceptors bring to the world of web development. These unsung heroes are the secret ingredients that transform Axios from an ordinary HTTP client into an extraordinary tool. Interceptors empower you to intercept and influence requests and responses as they traverse between your application and the server. This magical ability opens doors to a profusion of advantages:</p><p>From injecting authentication tokens seamlessly into every request, to handling errors with elegance and poise. Say goodbye to repetitive code, tangled error-handling mechanisms, and manual token injections — with interceptors, your application becomes smarter, cleaner, and remarkably efficient. In this journey, we’ll unravel the captivating world of Axios interceptors, discovering how they streamline workflows, fortify security, and elevate your development experience to a whole new level.</p><p><em>Understanding Axios Interceptors:</em></p><p>Axios interceptors are middleware functions that allow you to tap into the request and response flows. They offer a gateway to modify, authenticate, or handle errors at a centralized level.</p><p><em>Setting Up a Global Request Interceptor:</em></p><p>Imagine needing to include an authentication token in every request’s headers.Here is the solution to this hysteria with interceptor.</p><pre>axios.interceptors.request.use(config =&gt; {<br>  const authToken = localStorage.getItem(&#39;authToken&#39;);<br>  if (authToken) {<br>    config.headers.Authorization = `Bearer ${authToken}`;<br>  }<br>  return config;<br>});</pre><p><em>Streamlining Error Handling:</em></p><p>Interceptors are also adept at consolidating error handling. Say goodbye to scattered .catch blocks. Here&#39;s an example of catching and handling errors elegantly.</p><pre>axios.interceptors.response.use(<br>  response =&gt; response,<br>  error =&gt; {<br>    const status = error.response ? error.response.status : null;<br>    <br>    if (status === 401) {<br>      // Handle unauthorized access<br>    } else if (status === 404) {<br>      // Handle not found errors<br>    } else {<br>      // Handle other errors<br>    }<br>    <br>    return Promise.reject(error);<br>  }<br>);</pre><p><em>Optimizing Requests:</em></p><p>Interceptors enable data transformation before it reaches your application. This is particularly useful when data needs to be normalized or parsed. Imagine receiving an array of objects, but your app requires a specific format:</p><pre>axios.interceptors.response.use(response =&gt; {<br>  response.data = response.data.map(item =&gt; ({<br>    id: item.id,<br>    name: item.title<br>  }));<br>  return response;<br>});</pre><p><em>Refreshing Authentication Tokens:</em></p><p>In the context of authentication, interceptors can automatically refresh expired tokens. No more manually handling token refreshes:</p><pre>axios.interceptors.response.use(<br>  response =&gt; response,<br>  async error =&gt; {<br>    if (error.response.status === 401) {<br>      const newToken = await refreshToken();<br>      localStorage.setItem(&#39;authToken&#39;, newToken);<br>      // Retry the original request<br>      return axios(error.config);<br>    }<br>    return Promise.reject(error);<br>  }<br>);</pre><h3><strong>Use Cases For You (With Samples)</strong></h3><p>Scenario: Your e-commerce application requires an authentication token to be included in the headers of every API request for secure access to user data.</p><p>Explanation: User authentication is paramount in an e-commerce application to ensure that only authorized users can access sensitive data. Instead of manually adding the authentication token to each request, an Axios Interceptor can automate this process.</p><p>Imagine a scenario where a user is viewing their order history. To fetch this data, your application makes an API request as follows:</p><pre>axios.get(&#39;https://api.bbm.com/orders&#39;)<br>  .then(response =&gt; {<br>    // Handle successful response<br>    console.log(response.data);<br>  })<br>  .catch(error =&gt; {<br>    // Handle errors<br>    console.error(error);<br>  });</pre><p>Now, let’s add an interceptor to inject the authentication token:</p><pre>axios.interceptors.request.use(config =&gt; {<br>  const authToken = localStorage.getItem(&#39;authToken&#39;);<br>  if (authToken) {<br>    config.headers.Authorization = `Bearer ${authToken}`;<br>  }<br>  return config;<br>});</pre><p>With the interceptor in place, the same request will now automatically include the user’s authentication token.</p><p>Scenario: Your social media application interacts with multiple APIs, each returning different error structures. Consistently handling these errors is a challenge.</p><p>Explanation: In a social media application, API responses can include various error formats such as 404 errors for missing posts or 403 errors for unauthorized access. Instead of writing specific error-handling logic for each API call, you can use an interceptor to centralize error handling.</p><p>Suppose a user is trying to like a post:</p><pre>axios.post(&#39;https://api.bbm.com/posts/oppenheimer57ac38957/like&#39;)<br>  .then(response =&gt; {<br>    // Handle successful like<br>    console.log(response.data);<br>  })<br>  .catch(error =&gt; {<br>    // Handle errors<br>    console.error(error);<br>  });</pre><p>Now, let’s implement an interceptor to handle errors consistently:</p><pre>axios.interceptors.response.use(<br>  response =&gt; response,<br>  error =&gt; {<br>    const status = error.response ? error.response.status : null;<br>    <br>    if (status === 401) {<br>      // Handle unauthorized access<br>      console.log(&quot;Unauthorized access&quot;);<br>    } else if (status === 404) {<br>      // Handle not found errors<br>      console.log(&quot;Post not found&quot;);<br>    } else {<br>      // Handle other errors<br>      console.error(&quot;An error occurred:&quot;, error);<br>    }<br>    <br>    return Promise.reject(error);<br>  }<br>);</pre><p>With the interceptor, error handling is streamlined.</p><h3>Cancelling Interceptors</h3><p>Axios Interceptors can be powerful tools for managing API requests and responses, but there are scenarios where you might want to cancel or ignore certain interceptors for specific requests. Cancelling interceptors can be beneficial when you want to avoid unwanted side effects, such as applying global interceptors to requests where they’re not appropriate or necessary. There are several situations where cancelling interceptors might be necessary.</p><p><strong>Avoiding Duplicate Actions: </strong>If you have multiple interceptors that modify requests in a similar way (e.g., adding headers), you might want to cancel one of them to avoid duplication.</p><p><strong>Preventing Interference:</strong> Some requests might require a distinct set of interceptors due to their unique requirements. Cancelling certain interceptors can prevent interference with the intended behavior of these requests.</p><p><strong>Optimizing Performance:</strong> In cases where you have complex or resource-intensive interceptors, cancelling them for specific requests can help optimize performance and reduce unnecessary overhead.</p><p>To cancel an interceptor in Axios, you need to store the reference to the interceptor during its creation and then use the eject method to remove it.</p><pre>// Creating an interceptor and storing its reference<br>const axiosInterceptor = axios.interceptors.request.use(config =&gt; {<br>  // Modify the request config<br>  return config;<br>});<br><br>// Removing the interceptor<br>axios.interceptors.request.eject(axiosInterceptor);</pre><p>In the example above, myInterceptor is the reference to the interceptor. By calling axios.interceptors.request.eject(axiosInterceptor), you&#39;re removing that specific interceptor. This way, the interceptor will no longer affect subsequent requests.</p><p><strong>Scenario:</strong> You have a global request interceptor that adds an authorization token to the headers of every request. However, for a specific request, you want to exclude this token.</p><pre>// Creating a global request interceptor<br>const authInterceptor = axios.interceptors.request.use(config =&gt; {<br>  const authToken = localStorage.getItem(&#39;authToken&#39;);<br>  if (authToken) {<br>    config.headers.Authorization = `Bearer ${authToken}`;<br>  }<br>  return config;<br>});<br><br>// Making a request without the global interceptor<br>axios.get(&#39;https://api.bbm.com/get-oppenheimer-data&#39;)<br>  .then(response =&gt; {<br>    // Handle the response<br>    console.log(response.data);<br>  })<br>  .catch(error =&gt; {<br>    // Handle errors<br>    console.error(error);<br>  })<br>  .finally(() =&gt; {<br>    // Eject the interceptor to prevent it from affecting other requests<br>    axios.interceptors.request.eject(authInterceptor);<br>  });<br></pre><h3>Config For Axios Interceptor (With Sample)</h3><p><strong><em>1.Sending Data in Request Payload:</em></strong></p><pre>axios.interceptors.request.use(config =&gt; {<br>  config.data = {<br>    title: &#39;New Post&#39;,<br>    content: &#39;This is the content of the new post.&#39;<br>  };<br>  return config;<br>});<br><br>axios.post(&#39;https://api.bbm.com/posts&#39;)<br>  .then(response =&gt; {<br>    console.log(response.data);<br>  })<br>  .catch(error =&gt; {<br>    console.error(error);<br>  });</pre><p><strong><em>2. Handling Query Parameters:</em></strong></p><pre>axios.interceptors.request.use(config =&gt; {<br>  config.params = {<br>    category: &#39;oppenheimer&#39;,<br>    limit: 42<br>  };<br>  return config;<br>});<br><br>axios.get(&#39;https://api.bbm.com/posts&#39;)<br>  .then(response =&gt; {<br>    console.log(response.data);<br>  })<br>  .catch(error =&gt; {<br>    console.error(error);<br>  });</pre><p><strong><em>3. Uploading Files using </em></strong><strong><em>FormData with an Interceptor:</em></strong></p><pre>axios.interceptors.request.use(config =&gt; {<br>  if (config.data instanceof FormData) {<br>    config.headers[&#39;Content-Type&#39;] = &#39;multipart/form-data&#39;;<br>  }<br>  return config;<br>});<br><br>const formData = new FormData();<br>formData.append(&#39;oppenheimer-file&#39;, fileInput.files[0]);<br><br>axios.post(&#39;https://api.bbm.com/upload&#39;, formData)<br>  .then(response =&gt; {<br>    console.log(response.data);<br>  })<br>  .catch(error =&gt; {<br>    console.error(error);<br>  });</pre><p><strong><em>4. Handling Timeouts with an Interceptor:</em></strong></p><pre>axios.interceptors.request.use(config =&gt; {<br>  config.timeout = 4200; // Set a timeout of 4.2 seconds<br>  return config;<br>});<br><br>axios.get(&#39;https://api.bbm.com/data&#39;)<br>  .then(response =&gt; {<br>    console.log(response.data);<br>  })<br>  .catch(error =&gt; {<br>    if (error.code === &#39;ECONNABORTED&#39;) {<br>      console.error(&#39;Request timed out&#39;);<br>    } else {<br>      console.error(error);<br>    }<br>  });</pre><p><strong><em>5. Canceling Requests with Axios Cancel Tokens and Interceptor:</em></strong></p><pre>const CancelToken = axios.CancelToken;<br>const source = CancelToken.source();<br><br>axios.interceptors.request.use(config =&gt; {<br>  config.cancelToken = source.token;<br>  return config;<br>});<br><br>axios.get(&#39;https://api.bbm.com/data&#39;)<br>  .then(response =&gt; {<br>    console.log(response.data);<br>  })<br>  .catch(thrown =&gt; {<br>    if (axios.isCancel(thrown)) {<br>      console.log(&#39;Request canceled&#39;, thrown.message);<br>    } else {<br>      console.error(thrown);<br>    }<br>  });<br><br>// Cancel the request<br>source.cancel(&#39;Request canceled by the user.&#39;);</pre><p>In the realm of web development, where efficient data exchange is paramount, Axios emerges as a formidable ally. In this journey through the world of Axios interceptors, we’ve uncovered a treasure trove of capabilities that can revolutionize the way we handle API requests and responses. From seamlessly injecting authentication tokens to streamlining error handling and optimizing data transformations, interceptors offer a toolkit that empowers developers to craft more elegant, secure, and performant applications. As you venture forward, remember that interceptors are not just about functionality; they’re about achieving cleaner code, consistent behaviors, and a more pleasant development experience. With Axios interceptors, you’re not just making API calls; you’re shaping the future of your applications with every well-timed intercept. So go forth, embrace these interceptors, and elevate your web development journey to new heights.</p><p><strong>Thanks for reading — BBM</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db46653b7303" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>