<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Saverio683</title>
    <description>The latest articles on Forem by Saverio683 (@saverio683).</description>
    <link>https://forem.com/saverio683</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F751580%2F18dd4236-9fdc-4fbb-8b9c-1105b0c75393.jpg</url>
      <title>Forem: Saverio683</title>
      <link>https://forem.com/saverio683</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/saverio683"/>
    <language>en</language>
    <item>
      <title>Simple chat using sockets in Java</title>
      <dc:creator>Saverio683</dc:creator>
      <pubDate>Tue, 06 Dec 2022 18:01:16 +0000</pubDate>
      <link>https://forem.com/saverio683/sockets-in-java-p2d</link>
      <guid>https://forem.com/saverio683/sockets-in-java-p2d</guid>
      <description>&lt;p&gt;Hello everyone 👋, I hope you are doing well.&lt;br&gt;
In this post I'll talk about how to use sockets in Java.&lt;/p&gt;
&lt;h1&gt;
  
  
  📘 INTRODUCTION
&lt;/h1&gt;

&lt;p&gt;In order to make it possible to exchange messages between two nodes, we make use of &lt;strong&gt;sockets&lt;/strong&gt;.&lt;br&gt;
In simple terms, a socket is the pairing of an &lt;em&gt;IP&lt;/em&gt; and a &lt;em&gt;network port&lt;/em&gt; where packets will be sent/received by hosts.&lt;/p&gt;

&lt;p&gt;Sockets are divided into 2 groups, based on the transport protocol implemented: &lt;em&gt;tcp sockets&lt;/em&gt; and &lt;em&gt;udp sockets&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;In short, &lt;strong&gt;TCP&lt;/strong&gt; (Transmission Control Protocol) is a connection-oriented protocol that ensures that packets are sent correctly, which is useful for &lt;strong&gt;one-to-one connections&lt;/strong&gt;.&lt;br&gt;
On the other hand, &lt;strong&gt;UDP&lt;/strong&gt; (User Datagram Protocol) is a non-connection-oriented protocol used when it is acceptable to lose a few packets in favor of speed (such as in video games or streaming platforms), useful for &lt;strong&gt;one-to-many connections&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;In Java there are classes that implement both types of sockets.&lt;/p&gt;
&lt;h1&gt;
  
  
  SOCKET and SERVERSOCKET
&lt;/h1&gt;

&lt;p&gt;In a basic TCP connection we need a &lt;strong&gt;server&lt;/strong&gt; (ServerSocket class) and a &lt;strong&gt;client&lt;/strong&gt; (Socket class).&lt;br&gt;
In the example below, I have implemented a simple network where the server is constantly listening to client requests and assigning it a thread (so as to allow multi-user):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package test;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
    static final int PORT = 1234;

    public static void main(String args[]) {        
        System.out.println("Server listening on port "+PORT+"...");

        try {
            ServerSocket server = new ServerSocket(PORT);    

            while(true) {//listening for client connections
                try {
                    Socket socket = server.accept();//Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made.

                    ServerThread st = new ServerThread(socket);//assigning a thread to communicate with the client
                    st.start();

                    System.out.println("Connection established, thread assigned: "+st.getName());
                }
                catch(Exception e) {
                    e.printStackTrace();
                    System.out.println("Connection error");
                    server.close();       
                }
            }
        }
        catch(IOException e) {
            e.printStackTrace();
            System.out.println("Server error");
        }
    }   
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The thread that will be assigned to connect with that client will simply respond to its messages:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerThread extends Thread {
    private Socket socket;

    public ServerThread(Socket s) {
        super();
        this.socket = s;
    }

    //override of the run method
    public void run() {
        try {         
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));//for reading client messages
            PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);//to send messages to client

            while(true) {
                String incoming = br.readLine();//listening for the client messages    

                pw.println("You sent me this: "+incoming);//responding to the client
            }  
        } catch (IOException e) {
            System.out.println(this.getName()+": connection ended");
        } 
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On the client instead there will be 2 threads, one writing and one reading, so the user can send multiple messages while waiting for the response:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class TCPClient {
    static final int PORT = 1234;

    public static void main(String[] args) throws UnknownHostException, IOException {
        Socket socket = new Socket(InetAddress.getLocalHost(), PORT);//creates the socket, then connects to the server

        BufferedReader serverReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));//for reading server messages
        BufferedReader userReader = new BufferedReader(new InputStreamReader(System.in));//for reading user inputs
        PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);//to send messages to the server

        ClientReader cr = new ClientReader(serverReader);
        ClientWriter cw = new ClientWriter(pw, userReader);

        cr.start();
        cw.start();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Write thread&lt;/em&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

public class ClientWriter extends Thread {
    private PrintWriter pw;
    private BufferedReader stdin;

    public ClientWriter(PrintWriter pw, BufferedReader stdin) {
        this.pw = pw;
        this.stdin = stdin;
    }

    public void run() {

        while (true) {//l'utente invia messaggi finchè la comunicazione col server non si interrompe           
            try {
                String clientInput = stdin.readLine();//reading user input

                pw.println(clientInput);//sending user input to the server
            } catch(IOException e) {
                System.out.println("Client i/o error");
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Read thread&lt;/em&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package test;

import java.io.BufferedReader;
import java.io.IOException;

public class ClientReader extends Thread {
    private BufferedReader stdin;

    public ClientReader(BufferedReader stdin) {
        this.stdin = stdin;
    }

    public void run() {

        while (true) {
            try {
                String incoming = stdin.readLine();//reading server messages

                System.out.println(incoming);
            } catch(IOException e) {
                System.out.println("Client i/o error");
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example of communication, the client can only communicate with the server and not with other clients.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Here is an example from the console&lt;/em&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6d4r3cdtpv82x46zvub0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6d4r3cdtpv82x46zvub0.png" alt="Server"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvt13bn8mjbumqm1uy77o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvt13bn8mjbumqm1uy77o.png" alt="Client"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  DATAGRAMSOCKET and MULTICASTSOCKET
&lt;/h1&gt;

&lt;p&gt;On Java there is the &lt;strong&gt;DatagramSocket&lt;/strong&gt; class aimed at implementing this type of socket. Messages are exchanged in the form of bytes through datagram packets, implemented with the &lt;strong&gt;DatagramPacket&lt;/strong&gt; class, through the &lt;em&gt;send&lt;/em&gt; and &lt;em&gt;receive&lt;/em&gt; functions.&lt;/p&gt;

&lt;p&gt;The one below is an example of a broadcast connection where each host can send/receive messages to/from &lt;strong&gt;all&lt;/strong&gt; hosts on the network, without passing through a server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package udp;

import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class UDPHost {
    static final int PORT = 8290;

    public static void main(String[] args) throws SocketException, UnknownHostException {
        DatagramSocket senderSocket = new DatagramSocket();
        senderSocket.setBroadcast(true);

        DatagramSocket receiveSocket = new DatagramSocket(null);//all read sockets will be listening on the same port
        receiveSocket.setReuseAddress(true);
        receiveSocket.bind(new InetSocketAddress(PORT));

        UDPReader r = new UDPReader(receiveSocket);
        UDPWriter w = new UDPWriter(senderSocket, PORT);

        r.start();
        w.start();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code above, we need to invoke the &lt;strong&gt;setBroadcast&lt;/strong&gt; method to let the operating system know that the package will be broadcasted.&lt;/p&gt;

&lt;p&gt;Now, to send a broadcast message it is not necessary to know the ip of the destination target; rather, you only need to send to the &lt;strong&gt;broadcast address&lt;/strong&gt; of the &lt;strong&gt;network interface&lt;/strong&gt;, which will take care of sending the packet then to the hosts on it.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Write thread&lt;/em&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package udp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.NetworkInterface;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.Objects;

public class UDPWriter extends Thread {
    private DatagramSocket socket;
    private int port;

    public UDPWriter(DatagramSocket s, int p) {
        super();        
        this.socket = s;
        this.port = p;
    }

    public void run() {
        try {   
            BufferedReader userReader = new BufferedReader(new InputStreamReader(System.in));//reading user inputs

            while(true) {       
                byte[] sendData = userReader.readLine().getBytes(StandardCharsets.UTF_8);//saves the user input to the buffer
                broadcast(sendData);//sends the packet to all sockets on the network
            } 
        } catch (IOException e) {
            System.out.println(this.getName()+": error sending message");
        }
    }

    public void broadcast(byte[] buffer) throws IOException {
        Enumeration&amp;lt;NetworkInterface&amp;gt; interfaces = NetworkInterface.getNetworkInterfaces();
        while(interfaces.hasMoreElements()) {//iterates all network interfaces on the pc to get the ips of the other hosts where to send the broadcast message
            NetworkInterface networkInterface = interfaces.nextElement();

            if (networkInterface.isUp() || !networkInterface.isLoopback()) {//verifies the integrity of the network interface
                networkInterface.getInterfaceAddresses().stream() 
                    .map(interfaceAddress -&amp;gt; interfaceAddress.getBroadcast())
                    .filter(Objects::nonNull)
                    .forEach(ip -&amp;gt; {//iterate over the ips
                        try {
                            socket.send(new DatagramPacket(buffer, buffer.length, ip, port));//sending the packet
                        } catch (IOException e) {
                            System.out.println(this.getName()+": error sending message");
                        }   
                    });
            }
        }
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Read thread&lt;/em&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPReader extends Thread {
    private DatagramSocket socket;

    public UDPReader(DatagramSocket s) {
        super();
        this.socket = s;
    }

    public void run() {     
        while(true) {           
            try {
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);//messages travel as bytes through datagram packets
                socket.receive(receivePacket);//The socket remains listening for the datagram packet and then saves it to the buffer

                String incoming = new String(receiveData);
                System.out.println(incoming);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Broadcasting messages, however, is often inefficient because packets do not arrive only at the desired hosts but rather at all of them.&lt;/p&gt;

&lt;p&gt;To remedy this, there are &lt;strong&gt;multicast sockets&lt;/strong&gt; that allow a &lt;strong&gt;one-to-many&lt;/strong&gt; connection instead of one-to-all.&lt;br&gt;
The concepts are the same as for datagram sockets. In fact, the MulticastSocket class is nothing more than an extension of the DatagramSocket class; the packets sent are implemented with the DatagramPacket class.&lt;/p&gt;

&lt;p&gt;It is possible to send packets only to the desired hosts due to &lt;strong&gt;multicast groups&lt;/strong&gt;: a portion of network traffic, associated only with sockets joining it, that is identified by a &lt;em&gt;multicast address&lt;/em&gt; (any address between 224.0.0.0 to 239.255.255.255).&lt;br&gt;
Sockets can &lt;em&gt;join&lt;/em&gt; and &lt;em&gt;leave&lt;/em&gt; groups via the same-named functions.&lt;br&gt;
To send packets, the &lt;em&gt;send&lt;/em&gt; function is already implemented since you pass the name of the network card in the joinGroup method.&lt;/p&gt;

&lt;p&gt;Here an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package multicast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;

public class MulticastHost {
    static final int PORT = 1234; 

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//reading user inputs
        MulticastSocket socket = new MulticastSocket(PORT);
        InetAddress ip = null;

        boolean wrongUserInput = true;
        System.out.println("Select a room: a) gossib b) brainstorming c) soccer");

        while(wrongUserInput) {
            wrongUserInput = false;         

            switch(br.readLine()) {
                case "a":
                    ip = InetAddress.getByName("230.0.0.1");
                    break;
                case "b":
                    ip = InetAddress.getByName("230.0.0.2");
                    break;
                case "c":
                    ip = InetAddress.getByName("230.0.0.3");                    
                    break;
                default:
                    System.out.println("wrong room entered, please retry");
                    wrongUserInput = true;
                    break;
            }
        }

        InetSocketAddress address = new InetSocketAddress(ip, PORT);
        NetworkInterface netIf = NetworkInterface.getByName("wlo1");//obtained by typing from terminal the command "ifconfig" (linux)

        socket.joinGroup(address, netIf);
        socket.setBroadcast(true);

        MulticastWriter w = new MulticastWriter(socket, br, ip);
        MulticastReader r = new MulticastReader(socket, ip);

        w.start();
        r.start();

    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Write thread&lt;/em&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package multicast;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.nio.charset.StandardCharsets;

public class MulticastWriter extends Thread {
    private MulticastSocket socket;
    private BufferedReader br;
    private InetAddress ip;

    public MulticastWriter(MulticastSocket s, BufferedReader b, InetAddress i) {
        this.socket = s;
        this.br = b;
        this.ip = i;
    }

    private void send(String msg) throws IOException {   

        byte[] msgBytes = msg.getBytes(StandardCharsets.UTF_8);

        DatagramPacket ds = new DatagramPacket(msgBytes, msgBytes.length, ip, socket.getLocalPort());
        socket.send(ds);    
    }

    public void run() {             
        while(true) {
            try {
                String userInput = br.readLine();
                send(userInput);//sending user message to other clients in the same group
            } catch (IOException e) {
                System.out.println(this.getName()+": error sending message");
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Read thread&lt;/em&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package multicast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class MulticastReader extends Thread {
    private MulticastSocket socket;
    private InetAddress ip;

    public MulticastReader(MulticastSocket s, InetAddress i) {
        this.socket = s;
        this.ip = i;
    }

    private void listen() throws IOException {      
        byte[] buf = new byte[1024];
        DatagramPacket recv = new DatagramPacket(buf, buf.length, ip, socket.getLocalPort());
        socket.receive(recv);

        String incoming = new String(buf);
        System.out.println(incoming);
    }

    public void run() {
        while(true) {
            try {
                listen();
            } catch (IOException e) {
                System.out.println(this.getName()+": error listening incoming messages");
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Here is an example from the console:&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8c5ilqobbm3wy5pddf75.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8c5ilqobbm3wy5pddf75.png" alt="Screenshot"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F64q66s2czxsfaxgf98fi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F64q66s2czxsfaxgf98fi.png" alt="Screenshot"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnp27jxgxadesdsuutc6o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnp27jxgxadesdsuutc6o.png" alt="Screenshot"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  🔎 CONCLUSIONS
&lt;/h1&gt;

&lt;p&gt;Thank you for reading 🙂! I hope you enjoyed the post and that it may have been helpful to you, if so please leave a like.&lt;/p&gt;

&lt;p&gt;You can also see the code in this &lt;a href="https://github.com/Saverio683/Java-sockets" rel="noopener noreferrer"&gt;github repo&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;You can follow me to stay updated on my new posts.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Mastering JavaScript 🧑‍💻: Closures</title>
      <dc:creator>Saverio683</dc:creator>
      <pubDate>Sat, 10 Sep 2022 07:35:51 +0000</pubDate>
      <link>https://forem.com/saverio683/mastering-javascript-closures-3ij8</link>
      <guid>https://forem.com/saverio683/mastering-javascript-closures-3ij8</guid>
      <description>&lt;p&gt;Hello everyone 👋, I hope you are doing well.&lt;/p&gt;

&lt;p&gt;In this post I will explain what closures are using examples as well so that you too can use them to write your code better.&lt;/p&gt;

&lt;h2&gt;
  
  
  LEXICAL SCOPE ✍️
&lt;/h2&gt;

&lt;p&gt;Before directly explaining what closures are, it is appropriate to explain the concept of &lt;strong&gt;scope&lt;/strong&gt; and &lt;strong&gt;lexical scope&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The scope of a function refers that area of code where its variables are "visible" and can be used.&lt;br&gt;
If another function is created within one function, another internal scope will then be created, and so on: this is called a &lt;em&gt;scope chain&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Lexical scope&lt;/em&gt;, also called &lt;em&gt;static scope&lt;/em&gt;, refers to when the location of a function's &lt;em&gt;&lt;strong&gt;definition&lt;/strong&gt;&lt;/em&gt; determines which variables you have access to.&lt;/p&gt;

&lt;p&gt;E.g. :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const life = () =&amp;gt; {
  const pastEvents = 'past'

  //console.log(actualEvents) this will create an error because that inner variable is not accesible here

  const present = () =&amp;gt; {    
    const actualEvents = 'present'

    console.log(pastEvents, actualEvents)//ok
    //console.log(futureEvents) same for this one

    const future = () =&amp;gt; {
      const futureEvents = 'future'

      console.log(pastEvents, actualEvents, futureEvents)//ok      
    }

    future()
  }

  present()
}

life()
/*
Outputs:
  past present
  past present future
*/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, in a nested group of functions the inner functions have access to the variables and other resources of their parent scope.&lt;/p&gt;

&lt;h2&gt;
  
  
  CLOSURES 🪆
&lt;/h2&gt;

&lt;p&gt;Let's make some changes to the code from before:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const life = () =&amp;gt; {
  const pastEvents = 'past'

  const present = () =&amp;gt; {    
    const actualEvents = 'present'

    console.log(pastEvents, actualEvents)

    const future = () =&amp;gt; {
      const futureEvents = 'future'

      console.log(pastEvents, actualEvents, futureEvents)  
    }

    return future
  }

  return present
}

const newFunc = () =&amp;gt; {
  //different scope
  const newLife = life()
  const future = newLife()

  future() 
}

newFunc()
/*
Outputs:
  past present
  past present future
*/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;New functions created within the &lt;em&gt;newFunc&lt;/em&gt; function have access to the variables &lt;em&gt;pastEvents&lt;/em&gt;, &lt;em&gt;actualEvents&lt;/em&gt; and &lt;em&gt;futureEvents&lt;/em&gt; even if they are in another scope.&lt;br&gt;
This is because the &lt;em&gt;future&lt;/em&gt; and &lt;em&gt;present&lt;/em&gt; functions are closures: when they are assigned to variables (in our case &lt;em&gt;newLife&lt;/em&gt; and &lt;em&gt;future&lt;/em&gt;) they &lt;em&gt;&lt;strong&gt;close over&lt;/strong&gt;&lt;/em&gt; (from here the term closure) the variables of their lexical scope.&lt;/p&gt;

&lt;p&gt;Due to this the closures are &lt;em&gt;memory efficient&lt;/em&gt; saving code repetitions.&lt;br&gt;
Here another example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const addTo = x =&amp;gt; y =&amp;gt; x + y //x = outer func; y = inner.
const addToTen = addTo(10)
addToTen(3) // returns 13
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another benefit they bring is that of data &lt;em&gt;encapsulation&lt;/em&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const createCounter = () =&amp;gt; {
  let count = 0

  return {
    increment() {
      count++
    },
    decrement() {
      count--
    },
    showCount() {
      console.log(count)
    }
  }
}

const myCounter = createCounter()

for(let i = 0; i &amp;lt; 100; i++)
  myCounter.increment()

myCounter.decrement()

console.log(myCounter.count)//returns undefined
myCounter.showCount()//returns 99
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this way, the count variable is private and can be accessed only through proper functions written by the developer.&lt;/p&gt;

&lt;h2&gt;
  
  
  CONCLUSIONS
&lt;/h2&gt;

&lt;p&gt;If you have come this far in reading, I thank you. If you liked the post please leave a like and check out my other posts 🙂.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>Mastering JavaScript 🧑‍💻: How the js engine works</title>
      <dc:creator>Saverio683</dc:creator>
      <pubDate>Fri, 29 Jul 2022 22:02:00 +0000</pubDate>
      <link>https://forem.com/saverio683/mastering-javascript-how-the-js-engine-works-5a2p</link>
      <guid>https://forem.com/saverio683/mastering-javascript-how-the-js-engine-works-5a2p</guid>
      <description>&lt;p&gt;Hello everyone 👋, I hope you are doing well.&lt;/p&gt;

&lt;p&gt;With this post I plan to start a new section called &lt;em&gt;Mastering JavaScript&lt;/em&gt;, where I will expound on my knowledge of the programming language learned over time and I hope you find this content useful. &lt;/p&gt;

&lt;p&gt;With that said, let's get started!&lt;/p&gt;

&lt;h1&gt;
  
  
  📘 INTRODUCTION
&lt;/h1&gt;

&lt;p&gt;JavaScript is an &lt;strong&gt;interpreted&lt;/strong&gt; programming language and was born &lt;strong&gt;client-side&lt;/strong&gt;. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Interpreted&lt;/strong&gt; language means that the code, written by the programmer, is "read" line by line by an interpreter that simultaneously converts it into &lt;em&gt;binary code&lt;/em&gt;, understandable by the CPU so that it can be executed.&lt;/li&gt;
&lt;li&gt;It is called &lt;strong&gt;client-side&lt;/strong&gt; because the environment in which it runs is the browser, which is located in client devices such as smartphones, PCs, etc... &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;(Since 2009, JavaScript has also become server-side thanks to Node.js, but I will talk about that in a future post, here I would like to focus on the browser-side)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;So the element that is responsible for managing the js execution lifecycle is the &lt;em&gt;JavaScript engine&lt;/em&gt;, located inside the browser.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2gzwqyhsscvewx2eucud.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2gzwqyhsscvewx2eucud.png" alt="JS engine"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  🔎 HOW MANY TYPES OF ENGINES ARE THERE?
&lt;/h1&gt;

&lt;p&gt;Nowadays there are several engines implemented by various browsers that share many features. One of the first was &lt;strong&gt;SpiderMonkey&lt;/strong&gt; born in 1995 for the Netscape browser and is currently used by Mozilla Firefox, Chrome has &lt;strong&gt;V8&lt;/strong&gt; which is one of the most powerful, Safari uses &lt;strong&gt;Nitro&lt;/strong&gt; and so on and so for...&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7xk014ugy52ahcrdi0dx.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7xk014ugy52ahcrdi0dx.jpg" alt="Different Engines"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  ⚙️ HOW THE JS ENGINE WORKS
&lt;/h1&gt;

&lt;p&gt;Now that we know what a browser engine is, we can get more specific and find out how it works.&lt;/p&gt;

&lt;h3&gt;
  
  
  THE JS RUNTIME ENVIROMENT
&lt;/h3&gt;

&lt;p&gt;The runtime consists of the &lt;strong&gt;call stack&lt;/strong&gt; and the &lt;strong&gt;memory heap&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;strong&gt;stack&lt;/strong&gt; is a data structure that stores instructions to be executed and when they are executed they will be removed. The first thing that is added to the call stack is the &lt;em&gt;global execution context&lt;/em&gt; (or GEC). The GEC consists of the global object, which contains all the JavaScript built-ins and global variables written by the programmer (e.g. for the browser it's the &lt;em&gt;Window&lt;/em&gt; object).
Then other stacks will be added from the functions created by the developer.
So, when the code execution is finished, the last element to be removed from the stack will be the GEC.&lt;/li&gt;
&lt;li&gt;In the &lt;strong&gt;memory heap&lt;/strong&gt;, on the other hand, variables are stored dynamically: variables are allocated automatically when a function is called, and they are "deleted" automatically when the function exits. This is done by the garbage collector.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here is an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function one() {
  return 1
}

function two() {
  return one() + 1
}

function three() {
  return two() + 1
}

console.log(three())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpow3rb3hzo7zr5lrvghv.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpow3rb3hzo7zr5lrvghv.gif" alt="example"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Where &lt;em&gt;main()&lt;/em&gt; is the GEC.&lt;/p&gt;

&lt;p&gt;As we know, JavaScript allows it to be executed &lt;em&gt;asynchronously&lt;/em&gt; through special features contained in &lt;strong&gt;Web APIs&lt;/strong&gt;.&lt;br&gt;
In fact, it is within them that asynchronous functions are executed and not within the call stack (since we only have one).&lt;/p&gt;

&lt;p&gt;After that, their result of the API (the function in it) is put into the &lt;strong&gt;Callback Queue&lt;/strong&gt;, waiting for the call stack to clear. &lt;br&gt;
The engine is able to tell that the stack is empty and therefore needs to move the data from the Callback Queue thanks to the &lt;strong&gt;Event Loop&lt;/strong&gt;, which is nothing more than a listener that continuously monitors the stack.&lt;/p&gt;

&lt;p&gt;Here's an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log("start")

setTimeout(function() {
  console.log("1 sec delay")
}, 1000)

console.log("end")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fytasjjhgcj1dnzm8yr53.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fytasjjhgcj1dnzm8yr53.gif" alt="example 2"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So in the end the final pattern will look like this:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhnfe4hzuajqv2fmcu80p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhnfe4hzuajqv2fmcu80p.png" alt="JS Engine"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  THE JIT COMPILER
&lt;/h3&gt;

&lt;p&gt;As I said before, js is an interpreted language. &lt;br&gt;
But nowadays browsers like V8 have implemented &lt;strong&gt;just-in-time&lt;/strong&gt; or &lt;strong&gt;JIT compilers&lt;/strong&gt;, that is, they combine the features of both &lt;em&gt;interpreter&lt;/em&gt; and &lt;em&gt;compiler&lt;/em&gt; to achieve better performance.&lt;/p&gt;

&lt;p&gt;The interpreter as a pro takes very less time to analyze the source code but slowdowns can occur during code execution ( because it interprets the bytecode whenever a method is invoked, this would not be optimal e.g., in the presence of loops). &lt;br&gt;
On the other hand, the compiler scans the entire program and translates the whole of it into machine code at once, thus achieving greater stability and the overall time to execute the process is much slower.&lt;/p&gt;

&lt;p&gt;The JIT compiler manages to optimize time by interpreting the code, and assigns to the compiler only that which is reusable (such as methods) by compiling it into native machine language "just in time" to run.&lt;/p&gt;

&lt;h1&gt;
  
  
  🌐 RESOURCES
&lt;/h1&gt;

&lt;p&gt;&lt;a href="https://simonzhlx.github.io/js-engine/" rel="noopener noreferrer"&gt;JavaScript Engine, Call Stack, Callback Queue, Web API and Event Loop&lt;/a&gt;&lt;br&gt;
&lt;em&gt;(I got the gifs and examples from the link above)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Thank you for reading 🙂! I hope you enjoyed the post and that it may have been helpful to you, if so please leave a like. &lt;br&gt;
You can follow me to stay updated on my new posts.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>Portfolio template using React</title>
      <dc:creator>Saverio683</dc:creator>
      <pubDate>Tue, 04 Jan 2022 09:59:00 +0000</pubDate>
      <link>https://forem.com/saverio683/portfolio-template-using-react-10n8</link>
      <guid>https://forem.com/saverio683/portfolio-template-using-react-10n8</guid>
      <description>&lt;p&gt;Hello everyone! I recently created a portfolio template using React and React Router. &lt;br&gt;
It's quite simple to understand and easily customizable.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;The App.js&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In the App.js through react-router I render the pages:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5ncffkp6x1h98fcpbvh0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5ncffkp6x1h98fcpbvh0.png" alt="App code"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Home page&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The home page simply contains a background image and strings automatically generated with &lt;a href="http://mattboldt.github.io/typed.js/" rel="noopener noreferrer"&gt;typed.js&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7pcstiyisjbth0ph84ks.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7pcstiyisjbth0ph84ks.png" alt="Home page code"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;About page&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The about page, as the name implies, contains personal information and skills and in the &lt;a href="(https://github.com/Saverio683/portfolio-template/tree/main/src/assets/icons)"&gt;&lt;em&gt;icons&lt;/em&gt;&lt;/a&gt; folder, in the &lt;em&gt;assets&lt;/em&gt;, there are already many icons of programming languages and other ready-to-use icons.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F757xmwnkq4zy8f6c9h1p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F757xmwnkq4zy8f6c9h1p.png" alt="About page code"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Projects page&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The projects page is used to show your projects accompanied by a description.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwzqb1tvfl5mff8yqp7ck.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwzqb1tvfl5mff8yqp7ck.png" alt="Projects page code"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Contact page&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;On this page you can show your main profiles and through &lt;a href="https://www.emailjs.com" rel="noopener noreferrer"&gt;Emailjs&lt;/a&gt; you can send emails directly from the page itself. Here too in the &lt;a href="https://github.com/Saverio683/portfolio-template/tree/main/src/assets/icons" rel="noopener noreferrer"&gt;&lt;em&gt;icons&lt;/em&gt;&lt;/a&gt; folder there are already icons of the main social networks&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw8d02prc44jl60zi8zun.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw8d02prc44jl60zi8zun.png" alt="Contact page code"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Customization&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;All you need to do to modify the various personal fields in the project is contained in the &lt;a href="https://github.com/Saverio683/portfolio-template/blob/main/src/assets/datas.js" rel="noopener noreferrer"&gt;datas.js&lt;/a&gt; file and that's it!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://main.d1r809nyzjf6ax.amplifyapp.com/" rel="noopener noreferrer"&gt;Here&lt;/a&gt; you can see the live project and here the &lt;a href="https://github.com/Saverio683/portfolio-template" rel="noopener noreferrer"&gt;github repo&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I hope you liked the post, I invite you to comment and leave a review. Thank you.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Creating a weather app using React</title>
      <dc:creator>Saverio683</dc:creator>
      <pubDate>Sat, 04 Dec 2021 21:15:00 +0000</pubDate>
      <link>https://forem.com/saverio683/creating-a-weather-app-using-react-4oa1</link>
      <guid>https://forem.com/saverio683/creating-a-weather-app-using-react-4oa1</guid>
      <description>&lt;p&gt;Hello everyone, this is my first blog so I apologize if it won't be written well.&lt;/p&gt;

&lt;p&gt;Now let's get started!&lt;/p&gt;

&lt;p&gt;First of all, you need to get an API key. For this project I used the &lt;strong&gt;free&lt;/strong&gt; one from &lt;a href="https://openweathermap.org/price"&gt;OpenWeatherMap&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Once this is done we can move on to the code:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The folder structure&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Y064qnbt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aqslh7c795tc1dkyy5t2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Y064qnbt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aqslh7c795tc1dkyy5t2.png" alt="folders" width="377" height="687"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the &lt;em&gt;app&lt;/em&gt; folder there is the App.js file and the files that depend on it, I created this folder just to have more order but it could perfectly well not be there. In the &lt;em&gt;pages&lt;/em&gt; folder there are the pages that will be rendered by the App.js via &lt;a href="https://reactrouter.com/"&gt;reac-router&lt;/a&gt;.The &lt;em&gt;components&lt;/em&gt; folder as the name implies contains components such as the &lt;em&gt;icons&lt;/em&gt;. &lt;br&gt;
For handling the API response data I used &lt;a href="https://redux.js.org/"&gt;redux&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How the API works&lt;/strong&gt;&lt;br&gt;
This project, after entering the name of the city and possibly also the country, will give you the &lt;strong&gt;current&lt;/strong&gt; and &lt;strong&gt;daily&lt;/strong&gt; forecasts. To get both forecasts it is necessary to make 2 API calls: the first will give you the current forecast via the &lt;em&gt;name&lt;/em&gt; of the city entered; the second one obtains the data through the &lt;em&gt;geographical coordinates&lt;/em&gt; of the place (which are obtained from the first call).&lt;br&gt;
They are inserted by the user into the &lt;em&gt;SearchField&lt;/em&gt; component that through the onFormSubmit function pass the city name to &lt;em&gt;fetchData&lt;/em&gt; that makes the API request through redux.&lt;/p&gt;

&lt;p&gt;The SearchField component:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--U8NI0jz9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cthjgpkb1ymo190mh5bb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--U8NI0jz9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cthjgpkb1ymo190mh5bb.png" alt="SearchField component" width="812" height="873"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The redux reducer: &lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--9jVbpo0E--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xbaj37xd7zw6fxjrgg1b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--9jVbpo0E--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xbaj37xd7zw6fxjrgg1b.png" alt="reducer" width="728" height="975"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The fetchData action:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--zggenop0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/59rhqyjelet8s8y5jliw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zggenop0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/59rhqyjelet8s8y5jliw.png" alt="fetchData action" width="880" height="354"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The components&lt;/strong&gt;&lt;br&gt;
The two main components are the &lt;em&gt;CurrentForecast&lt;/em&gt; and the &lt;em&gt;DailyForecast&lt;/em&gt;. Both containers render other components to display the data&lt;/p&gt;

&lt;p&gt;The CurrentData component: &lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_BC2YAEr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5pi3w1ujwprpee1mdh4p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_BC2YAEr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5pi3w1ujwprpee1mdh4p.png" alt="CurrentData" width="880" height="303"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The DailyData component:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--VQ8cIUOJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b8oq2ga934r4wirym5ew.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--VQ8cIUOJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b8oq2ga934r4wirym5ew.png" alt="DailyData" width="880" height="270"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Routing&lt;/strong&gt;&lt;br&gt;
In this project, if you click on a day of the daily forecast, you go to the page where the details on the forecast of that day are shown. The redirect of the pages is done via react-router in the &lt;em&gt;App.js&lt;/em&gt;:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--qFdanN2m--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7bipfu3albhije6221o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qFdanN2m--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7bipfu3albhije6221o.png" alt="App.js" width="880" height="533"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The details page simply shows the CurrentForecast component with the details of that specific day:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--iQ9T1439--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/go03q7v4ue2yznakalmv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--iQ9T1439--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/go03q7v4ue2yznakalmv.png" alt="details page" width="880" height="440"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That's pretty all. You can see all the files on github:&lt;br&gt;
&lt;a href="https://github.com/Saverio683/weather-app-project"&gt;https://github.com/Saverio683/weather-app-project&lt;/a&gt;&lt;br&gt;
here the finished site: &lt;br&gt;
&lt;a href="https://master.d1aih8wyl9juxv.amplifyapp.com/"&gt;https://master.d1aih8wyl9juxv.amplifyapp.com/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Thank you for paying your attention to this post. I hope it was helpful to you.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
