<?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 Usman Saleem on Medium]]></title>
        <description><![CDATA[Stories by Usman Saleem on Medium]]></description>
        <link>https://medium.com/@usmansaleem29?source=rss-2662f5f1691b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CA1dvSVV-ZlWpFCu44MIIQ.jpeg</url>
            <title>Stories by Usman Saleem on Medium</title>
            <link>https://medium.com/@usmansaleem29?source=rss-2662f5f1691b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 09:44:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@usmansaleem29/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[Build a Chat Room With Node.js and Socket.io]]></title>
            <link>https://medium.com/swlh/build-a-chat-room-with-node-js-and-socket-io-e3e43f49a02d?source=rss-2662f5f1691b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3e43f49a02d</guid>
            <category><![CDATA[chat]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[room]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Usman Saleem]]></dc:creator>
            <pubDate>Tue, 22 Dec 2020 21:13:07 GMT</pubDate>
            <atom:updated>2021-02-01T11:07:11.152Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*Q5iAbEm4ZuM4RpNlJTI4Hg.jpeg" /><figcaption>Image by <a href="https://www.slideshare.net/EyalV/nodejs-socketio-37327827">EyalV</a> via <a href="https://www.slideshare.net/EyalV/nodejs-socketio-37327827">slideshare</a></figcaption></figure><p>I have been working with node.js for quite some time . I started off as a Mean stack developer and now working in Mern stack which is amazing. Every JavaScript framework is interesting and has its own taste. I like node because it’s fast due to its non-blocking and single-threaded nature. While i was learning, i came across a library for chat which is Socket.IO.</p><h3>Introduction</h3><p>Socket.IO is a library that enables real-time, duplex communication between client and the server.</p><p>It contains <strong>Websocket</strong> which is a protocol that provides a full-duplex and low-latency channel between the server and the browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*47FMxjiu-uLI0MmY.png" /><figcaption>via <a href="https://socket.io/docs/v3">socket.io/docs/v3</a></figcaption></figure><h3>Implementation in Node.js:</h3><h4>Basic overview:</h4><ul><li>const socketio = require(“socket.io”) // To get the package</li><li>const io = socketio(server) // here sever is http-server</li><li>io.on(‘connect’, ()=&gt;{}) // this is first function called when connection is made between client and server</li><li>socket.on(‘join’, ()=&gt; {}) and socket.join(‘user room’) //these events for joining the room</li><li>socket.emit(‘name of event’, ()=&gt;{}) // it emits the event which both client or server will listen to</li><li>socket.on(‘name of event’,()=&gt;{}) this is used both in client side and server side to listen to the event which is emitted by socket.emit and run the code inside it</li><li>socket.on(‘disconnect’,()=&gt;{}) // it will tell when the user has disconnected</li></ul><h4>Server code integration (node):</h4><pre>create and cd SampleApp </pre><pre>npm init // to setup npm package</pre><pre>npm i --save express // i am using express.js</pre><pre>npm i --save <strong>socket.io</strong> // for socket.io</pre><p>After everything is installed. Create a file name server.js and started writing the code</p><h4>server.js</h4><pre>const http = require(&#39;http&#39;);<br>const express = require(&#39;express&#39;);<br>const socketio = require(&#39;socket.io&#39;);<br>const app = express();</pre><pre>const server = http.createServer(app);<br>const io = socketio(server);</pre><pre>const {<br>  addUser,<br>  removeUser,<br>  getUser,<br>  getUsersInRoom<br>} = require(&#39;./utils/User&#39;);</pre><pre>io.on(&#39;connect&#39;, socket =&gt; {<br>  socket.on(&#39;join&#39;, ({ username, room }, callback) =&gt; {<br>    const { error, user } = addUser({ id: socket.id, name: username, room }); // add user with socket id and room info<br><br>    if (error) return callback(error);<br><br>    socket.join(user.room);<br><br>    socket.emit(&#39;message&#39;, {<br>      user: &#39;adminX&#39;,<br>      text: `${user.name.toUpperCase()}, Welcome to ${user.room} room.`<br>    });<br>    socket.broadcast.to(user.room).emit(&#39;message&#39;, {<br>      user: &#39;adminX&#39;,<br>      text: `${user.name.toUpperCase()} has joined!`<br>    });<br><br>    io.to(user.room).emit(&#39;roomData&#39;, {<br>      room: user.room,<br>      users: getUsersInRoom(user.room) // get user data based on user&#39;s room<br>    });<br><br>    callback();<br>  });</pre><pre>socket.on(&#39;sendMessage&#39;, (message, callback) =&gt; {<br>  const user = getUser(socket.id);<br><br>  io.to(user.room).emit(&#39;message&#39;, { user: user.name, text: message });<br><br>  callback();<br>});</pre><pre>socket.on(&#39;disconnect&#39;, () =&gt; {<br>  const user = removeUser(socket.id);<br><br>  if (user) {<br>    io.to(user.room).emit(&#39;message&#39;, {<br>      user: &#39;adminX&#39;,<br>      text: `${user.name.toUpperCase()} has left.`<br>    });<br>    io.to(user.room).emit(&#39;roomData&#39;, {<br>      room: user.room,<br>      users: getUsersInRoom(user.room)<br>    });<br>  }<br>});</pre><pre>server.listen(process.env.PORT || 3000, () =&gt;<br>  <strong><em>console</em></strong>.log(&#39;Server is running&#39;)<br>);</pre><p>after establishing the connection and user joins the room. There will be a socket.emit event which will be listened by socket.on<br>socket.on(‘sendMessage’) event will be listened which contains user name and message. After this connection will be disconnected when user leaves the chat and an event will be emitted.</p><p>Create a user.js file for user crud</p><h4>users.js</h4><pre>//Array of users<br>const users = [];<br><br>const addUser = ({ id, name, room }) =&gt; {<br>  name = name.trim().toLowerCase();<br>  room = room.trim().toLowerCase();<br><br>  const existingUser = users.find(<br>    user =&gt; user.room === room &amp;&amp; user.name === name<br>  );<br><br>  if (!name || !room) return { error: &#39;Username and room are required.&#39; };<br>  if (existingUser) return { error: &#39;Username already exists.&#39; };<br><br>  const user = { id, name, room };<br><br>  users.push(user);<br><br>  return { user };<br>};<br><br>const removeUser = id =&gt; {<br>  const index = users.findIndex(user =&gt; user.id === id);<br><br>  if (index !== -1) return users.splice(index, 1)[0];<br>};<br><br>const getUser = id =&gt; users.find(user =&gt; user.id === id);<br><br>const getUsersInRoom = room =&gt; users.filter(user =&gt; user.room === room);<br><br>module.exports = { addUser, removeUser, getUser, getUsersInRoom };</pre><p>Same events will be listened at client as well. I am using React for front-end.</p><h4>Client code integration (React):</h4><pre>create and cd ClientSample</pre><pre>npm i --save socket.io-client // for socket.io client</pre><p>After installation. Create a file name clientSocket.js and add code like</p><pre>import { useState, useEffect, useRef } from &#39;react&#39;;<br>import socketIOClient from &#39;socket.io-client&#39;;<br><br>const ENDPOINT = &#39;http://localhost:3000/&#39;;<br><br>const ClientSocket = ({ username, room }) =&gt; {<br>  const socketRef = useRef();<br>  const [users, setUsers] = useState([]);<br>  const [messages, setMessages] = useState([]);<br>  const [error, setError] = useState(&#39;&#39;);<br><br>  useEffect(() =&gt; {<br>    socketRef.current = socketIOClient(ENDPOINT);<br><br>    socketRef.current.emit(&#39;join&#39;, { username, room }, error =&gt; {<br>      if (error) {<br>        setError(error);<br>      }<br>    });<br><br>    return () =&gt; {<br>      socketRef.current.emit(&#39;disconnect&#39;);<br>    };<br>  }, [username, room]);<br><br>  useEffect(() =&gt; {<br>    socketRef.current.on(&#39;message&#39;, message =&gt; {<br>      setMessages(messages =&gt; [...messages, message]);<br>    });<br><br>    socketRef.current.on(&#39;roomData&#39;, ({ users }) =&gt; {<br>      setUsers(users);<br>    });<br>  }, []);<br><br>  const sendMessage = message =&gt; {<br>    socketRef.current.emit(&#39;sendMessage&#39;, message, () =&gt; {});<br>  };<br><br>  return { users, messages, sendMessage, error };<br>};<br><br>export default ClientSocket;</pre><p>It will use same events which is used by server to emit or listen every time user gets a message. After this, create Chat.js file</p><pre>const Chat = () =&gt; {<br>  const history = useHistory();<br>  const { username, room } = useParams(); //these are added when      user registers</pre><pre>  const [message, setMessage] = useState(&#39;&#39;);</pre><pre>  const { users, messages, sendMessage} = ClientSocket({<br>      username,<br>      room<br>    });</pre><pre>  const onSubmitHandler = event =&gt; {<br>    event.preventDefault();<br>    if (message) sendMessage(message);<br>    setMessage(&#39;&#39;);<br>  }; </pre><pre>  const renderActiveUsers = () =&gt; {<br>    return users.map(user =&gt; {<br>      return (<br>        &lt;p key={user.id} &gt;<br>          &lt;i className=&quot;fa fa-circle&quot;&gt;&lt;/i&gt; {user.name}<br>        &lt;/p&gt;<br>      );<br>    });<br>  };</pre><pre>return (</pre><pre>  &lt;div className=&quot;container-fluid d-flex&quot;&gt;<br>   &lt;div className=&quot;col-lg-6&quot;&gt;<br>     &lt;ul&gt;<br>       &lt;h6&gt;Messages&lt;/h6&gt;<br>       {messages.text}<br>     &lt;/ul&gt;<br>     &lt;form onSubmit={onSubmitHandler}&gt; <br>       &lt;input<br>       autoComplete=&quot;off&quot;<br>       value={message}<br>       onChange={e =&gt; setMessage(e.target.value)}<br>       type=&quot;text&quot;<br>       name=&quot;message&quot;<br>      /&gt;</pre><pre>       &lt;button type=&quot;submit&quot;&gt; Send &lt;/button<br>    &lt;/form&gt;<br>  &lt;/div&gt;</pre><pre>&lt;div className=&quot;col-lg-6 border-left ml-2&quot;&gt;<br>     {renderActiveUsers()}<br>   &lt;/div&gt;<br> &lt;/div&gt;</pre><pre>)};<br>export default Chat;</pre><h3>Conclusion</h3><p>Above code is simple implementation of how we setup socket.IO in both client and server. It’s an awesome and easy to integrate library.</p><p>I wrote very minimal code to let you know about the socket.io. If you want to improve it you can:</p><ul><li>Write separate react(jsx) files to give it a chat app feel and apply styling.</li><li>Add online/offline labels</li></ul><p>Thank you for reading .Hope you like it. :)</p><h3>Reference</h3><ul><li><a href="https://socket.io/docs/v3">socket.io/docs/v3</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3e43f49a02d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/build-a-chat-room-with-node-js-and-socket-io-e3e43f49a02d">Build a Chat Room With Node.js and Socket.io</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add Multilanguage Support to Your React App]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/better-programming/add-multi-language-support-in-react-js-a771c9ab31c3?source=rss-2662f5f1691b------2"><img src="https://cdn-images-1.medium.com/max/1280/1*t-zOVs7OADfdJdvZclSvZQ.jpeg" width="1280"></a></p><p class="medium-feed-snippet">How you can internationalize your React app today</p><p class="medium-feed-link"><a href="https://medium.com/better-programming/add-multi-language-support-in-react-js-a771c9ab31c3?source=rss-2662f5f1691b------2">Continue reading on Better Programming »</a></p></div>]]></description>
            <link>https://medium.com/better-programming/add-multi-language-support-in-react-js-a771c9ab31c3?source=rss-2662f5f1691b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a771c9ab31c3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[internationalization]]></category>
            <dc:creator><![CDATA[Usman Saleem]]></dc:creator>
            <pubDate>Fri, 26 Jun 2020 20:38:53 GMT</pubDate>
            <atom:updated>2020-12-21T20:23:50.508Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to work with HTTP Interceptors in Angular]]></title>
            <link>https://medium.com/better-programming/how-to-work-with-http-interceptors-in-angular-65c026fff46b?source=rss-2662f5f1691b------2</link>
            <guid isPermaLink="false">https://medium.com/p/65c026fff46b</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[interceptors]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[https]]></category>
            <dc:creator><![CDATA[Usman Saleem]]></dc:creator>
            <pubDate>Sun, 27 Oct 2019 05:51:02 GMT</pubDate>
            <atom:updated>2020-12-11T11:02:33.058Z</atom:updated>
            <content:encoded><![CDATA[<h4>What are they and why you should use them?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*ILIaNMxummSwFPiYj4-PsQ.png" /></figure><p>I have been working in Angular for quite some time now and have worked on almost every version of it. It’s amazing how every version comes with new features. One feature that caught my eye is HttpInterceptor<strong>. </strong>It was first introduced in Angular 4.3 and it’s pretty useful.</p><h3>Introduction to Interceptors</h3><p>Interceptors provide a method to intercept an outgoing request or incoming response. They are very similar to the middleware, with a framework like Express, except for the frontend. Interceptors can be very useful for features like caching and logging.</p><blockquote>HttpInterceptor<strong> </strong>provides a way to intercept HTTP requests and responses to transform or handle them before passing them along.</blockquote><h3>Basic Implementation</h3><p>Creating an interceptor is pretty simple. You have to create a class that is @injectable<strong> </strong>and implements the HttpInterceptor:</p><pre>@Injectable()<br>export class ApiInterceptor implements HttpInterceptor {  </pre><pre>constructor() {}</pre><pre>intercept(req: HttpRequest&lt;<strong>any</strong>&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;<strong>any</strong>&gt;&gt; {<br>    <strong>const </strong>authReq = req.clone({<br>        //add original request and/or set/add new headers <br>    });<br>});<br>  <strong>return </strong>next.handle(authReq);<br> }<br>}</pre><p>This takes req<strong> </strong>and next<strong> </strong>as a parameter and returns HttpEvent<strong> </strong>as an observable.</p><p>After that you need to provide it in the AppModule<strong> </strong>like this:</p><pre>@NgModule({<br>  bootstrap: [AppComponent],<br>  imports: [...],<br>  providers: [<br>    {<br>      provide: HTTP_INTERCEPTORS,<br>      useClass: ApiInterceptor,<br>      multi: true<br>    }<br>  ]<br>})<br>export class AppModule {}</pre><p>This is the basic implementation of HttpInterceptor in a pretty simple way.</p><h3>Why Should You Use HttpInterceptors?</h3><p>HttpInterceptors can perform a variety of tasks, from authentication to logging, setting or adding headers, HTTP request and response, notifications, error handling, and showing a loader on every HTTP request. Without interceptors, developers would have to add these tasks manually for every HTTP client call.</p><h4>1. Set headers</h4><p>We can easily add <strong>authorization</strong> headers so we don’t have to add them separately in every request:</p><pre>const addHeaders= req.clone({ <br>   headers: req.headers<br>     .set(&#39;Authorization&#39;, `Bearer $token`)<br>     .set(&#39;Content-Type&#39;, &#39;application/json&#39;)<br>});<br>return next.handle(addHeaders);</pre><p>As you can see, it’s simple to manipulate headers in the interceptor.</p><h4>2. Show loader</h4><p>We can add a loader in the interceptor for every request. For this, we add a loader service which has show and hide loader methods. We can then show the loader for every request and hide it when the request is finalised:</p><pre>const loaderService = this.injector.get(LoaderService);<br><br>loaderService.show();<br><br>return next.handle(req).pipe(<br>  delay(5000),<br>  finalize(() =&gt; loaderService.hide())<br>);</pre><p>This is a better solution — we don’t have to call the loader service with every single API request.</p><h4><strong>3. Notifications</strong></h4><p>We can show a notification every time the response status is 200 or 201, which indicates success.</p><p>Here’s an example of object creation:</p><pre>return next.handle(req).pipe(<br>  tap((event: HttpEvent&lt;any&gt;) =&gt; {<br>    if (event instanceof HttpResponse &amp;&amp; event.status === 201) {<br>      this.toastr.success(&quot;Object created.&quot;);<br>    }<br>  })<br>);</pre><p>This will show the success toaster every time the response status is 201. This is pretty useful as you won’t have to explicitly add toaster in every API request.</p><h4><strong>4. Error handling</strong></h4><p>There are multiple cases which can cause an error in interceptor. We can use the retry operator inside the pipe function (which combines multiple functions) for the http request.</p><p>We use Retry from <strong>RxJS </strong>to resubscribe to the observable and in return we get a successful result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4a0de47dfb7547db836ee5dba51a286/href">https://medium.com/media/a4a0de47dfb7547db836ee5dba51a286/href</a></iframe><p>We can check the status of error and on that basis we can decide what to do with it.</p><p>In the above example we’re using the retry operator before checking the status of the exception. If the status isn’t 401 then we’re throwing a toaster error. So that’s how we will be handling error in interceptor.</p><p>With HttpInterceptors<strong>,</strong> we can do other things too like profiling, URL manipulation and more.</p><p>That’s pretty much it.</p><p>Thank you for reading. I hope it helps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65c026fff46b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-work-with-http-interceptors-in-angular-65c026fff46b">How to work with HTTP Interceptors in Angular</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>