<?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 Chisom Uma on Medium]]></title>
        <description><![CDATA[Stories by Chisom Uma on Medium]]></description>
        <link>https://medium.com/@chisomuma476?source=rss-77d4fc391b5a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1CzSAGOuH78zuGl4</url>
            <title>Stories by Chisom Uma on Medium</title>
            <link>https://medium.com/@chisomuma476?source=rss-77d4fc391b5a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:57:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chisomuma476/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[Building an E-Learning Portal with Role-Based Course Management using Next.js and Permit.io]]></title>
            <link>https://medium.com/@chisomuma476/building-an-e-learning-portal-with-role-based-course-management-using-next-js-and-permit-io-95342ac977e1?source=rss-77d4fc391b5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/95342ac977e1</guid>
            <dc:creator><![CDATA[Chisom Uma]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 15:12:37 GMT</pubDate>
            <atom:updated>2025-02-05T10:17:38.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9WlDv25RVyS247XpnVv7g.png" /></figure><p>Proper <a href="https://www.permit.io/blog/what-is-authorization">authorization</a> becomes an important business requirement when building an e-learning portal. And here is why: You need to authenticate users and verify that they have the appropriate permissions to perform specific actions.</p><p>For instance, not all instructors should be able to modify other instructors’ courses. Students should only be able to access courses they’ve enrolled in, and administrators must oversee the entire system. Your e-learning platform could face serious security and management issues without proper role-based access control.</p><p>This guide shows you how to build an E-Learning Portal with <a href="https://www.permit.io/blog/what-is-rbac">Role-Based</a> Course Management using Next.js and <a href="https://www.permit.io/">Permit.io</a>.</p><h3>What are we building?</h3><p>In this tutorial, we’ll be building an E-learning portal that allows:</p><ul><li>Administrators to create a system that manages all courses and users.</li><li>Instructors manage their courses and students.</li><li>Students access only their enrolled courses.</li></ul><p>By the end of this tutorial, you’ll have a fully functional e-learning platform with proper authorization controls.</p><p><strong>Note:</strong> To follow along with this tutorial, check out the project GitHub repo <a href="https://github.com/ChisomUma/testpermit">here</a>.</p><p>Here’s what our E-Learning portal looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DQRYOx-4kU3bQD_C" /></figure><h3>What is RBAC?</h3><p><a href="https://www.permit.io/blog/what-is-rbac">Role-Based Access Control (RBAC)</a> is a method of regulating access to computer or network resources based on the roles of individual users. The main components include:</p><ul><li><strong>Roles</strong>: Defined categories representing sets of permissions (e.g., Admin, Instructor, Student)</li><li><strong>Permissions</strong>: Specific actions that can be performed on resources (e.g., create, read, update, delete)</li><li><strong>Users</strong>: Individuals who are assigned roles</li><li><strong>Resources</strong>: Objects users interact with (e.g., courses, enrollments)</li></ul><h3>Project Overview</h3><p>We’re building an e-learning portal with these key features:</p><ul><li>User registration and role assignment</li><li>Course creation and management</li><li>Student enrollment system</li><li>Role-based access to different portal sections</li></ul><h3>Role Structure</h3><p>Here’s an overview of the pages and their access levels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*snY0WT-A0abkORLPcsFKCg.png" /></figure><p>Here are the detailed access permissions by role:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*0_ZL2J4S5NxOY2cfimlMvQ.png" /></figure><h3>Technical Requirements</h3><p>To follow along with this tutorial, you should have:</p><ul><li>Basic understanding of authentication and authorization</li><li>Experience with React and Next.js</li><li>A Permit.io account</li><li>Node.js installed on your machine</li></ul><h3>Project Setup</h3><p>To get started with our <a href="https://www.permit.io/blog/how-to-add-rbac-in-nextjs">RBAC implementation in Next.js</a>, let’s start by creating a new Next.js project and installing the necessary dependencies:</p><pre>npx create-next-app@latest e-learning-portal --typescript <br>cd e-learning-portal <br>npm install @supabase/ssr permitio</pre><h3>Database Schema</h3><p>Our application requires several tables to manage users, courses, and enrollments. Here is what the database schema looks like:</p><pre><br>// Database schema using Supabase<br>CREATE TYPE user_role AS ENUM (&#39;admin&#39;, &#39;instructor&#39;, &#39;student&#39;);<br><br>CREATE TABLE profiles (<br>  id UUID REFERENCES auth.users ON DELETE CASCADE PRIMARY KEY,<br>  email TEXT UNIQUE,<br>  full_name TEXT,<br>  role user_role DEFAULT &#39;student&#39;,<br>  created_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE(&#39;utc&#39;::text, NOW()) NOT NULL,<br>  updated_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE(&#39;utc&#39;::text, NOW()) NOT NULL<br>);<br><br>CREATE TABLE courses (<br>  id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,<br>  title TEXT NOT NULL,<br>  description TEXT,<br>  instructor_id UUID REFERENCES profiles(id) ON DELETE CASCADE,<br>  created_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE(&#39;utc&#39;::text, NOW()) NOT NULL,<br>  updated_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE(&#39;utc&#39;::text, NOW()) NOT NULL<br>);<br><br>CREATE TABLE enrollments (<br>  id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,<br>  course_id UUID REFERENCES courses(id) ON DELETE CASCADE,<br>  student_id UUID REFERENCES profiles(id) ON DELETE CASCADE,<br>  enrolled_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE(&#39;utc&#39;::text, NOW()) NOT NULL,<br>  UNIQUE(course_id, student_id)<br>);</pre><h3>Configuring Permit.io</h3><p>Permit.io is a critical middleware layer that decouples authorization logic from application code. This separation of concerns makes our permission system more maintainable and scalable as the application grows. Instead of embedding complex permission checks throughout our codebase, we can define our authorization rules in one central location through Permit.io’s intuitive dashboard.</p><p>The platform also provides real-time policy updates without requiring application redeployment, meaning we can adjust user permissions instantly when needed.</p><p>When integrated with our e-learning portal, Permit.io handles the heavy lifting of permission evaluation while maintaining fast response times through its distributed Policy Decision Points (PDPs). This allows our application to focus on its core functionality while ensuring robust and consistent access control across all features.</p><p>The coming sections follow some of the <a href="https://www.permit.io/blog/best-practices-to-implement-rbac-for-developers">best practices for implementing RBAC</a> — which you’ll find very useful as a developer.</p><p><strong>Setting Up Resources and Roles</strong></p><p>First, let’s create a new project in Permit.io and configure our resources. To do this, log in to Permit and create a new project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JPz1-IKcaW7UcJ4i" /></figure><p>Now navigate to the Policy section and create the following resources:</p><ul><li>Course</li><li>Enrollment</li><li>User</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*QIuWMT903szfDyhd" /></figure><p><strong>Creating User Roles</strong></p><p>In our e-learning portal, we need three main roles:</p><ul><li>Admin</li><li>Instructor</li><li>Student</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*mer7FHDE7jW0o2yj" /></figure><p>To create these roles:</p><ol><li>Go to the Policy section</li><li>Click on the Roles tab</li><li>Add each role</li></ol><h3>Define permissions for each role in the Policy Editor</h3><p>After creating the necessary roles, you need to add permissions to them by going to the policy editor in your Permit dashboard and checking the boxes of the actions you want possible for each role and resource.</p><p>Here is what our policies look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fjqaKsFpLATM7Zl3" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eaVFKUXHIYAt5YjL" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hahOqiu9IQB1mGCq" /></figure><p>Check out <a href="https://www.permit.io/blog/what-is-policy-as-code">this blog</a> to learn more about Permit’s policy as code.</p><h3>Implementing Permission Checks</h3><p>The core of our RBAC implementation lies in how we configure and use Permit.io to check permissions throughout our application. We’ll create a centralized configuration file that handles all permission-related functionality, making it easy to maintain and modify our authorization logic as needed.</p><p>Let’s set up our Permit.io configuration in a dedicated file. This file will serve as our permission management hub, providing reusable functions for checking user permissions across the entire application:</p><pre><br>// lib/permit.ts<br>import { Permit } from &#39;permitio&#39;;<br>import { unstable_cache } from &#39;next/cache&#39;;<br><br>const permit = new Permit({<br>  pdp: process.env.PERMIT_IO_PDP_URL,<br>  token: process.env.PERMIT_IO_API_KEY,<br>});<br><br>export type Actions = &#39;create&#39; | &#39;read&#39; | &#39;update&#39; | &#39;delete&#39;;<br>export type Resources = &#39;Course&#39; | &#39;Enrollment&#39; | &#39;User&#39;;<br><br>export async function syncUserWithPermit(userId: string, email: string) {<br>  try {<br>    const user = {<br>      key: userId,<br>      email,<br>      first_name: email.split(&quot;@&quot;)[0],<br>    };<br>    await permit.api.syncUser(user);<br>    return true;<br>  } catch (error) {<br>    console.error(&quot;Failed to sync user with Permit:&quot;, error);<br>    return false;<br>  }<br>}<br><br>const check = unstable_cache(<br>  async (action: Actions, resource: Resources, id: string) =&gt; {<br>    const permitted = await permit.check(id, action, resource);<br>    return permitted;<br>  },<br>  [&#39;permitKey&#39;],<br>  { revalidate: 600 }<br>);<br><br>export const checkPermission = async (action: Actions, resource: Resources) =&gt; {<br>  const user = await getUser();<br>  if (!user) throw new Error(&#39;No user found&#39;);<br><br>  return check(action, resource, user.id.toString());<br>};</pre><p>Let’s break down what each part of this configuration does:</p><ul><li>First, we initialize the Permit client with our environment variables. The pdp URL points to Permit&#39;s Policy Decision Point, which evaluates our permission requests, while the API key authenticates our application.</li><li>We have a utility function to sync a user to permit.</li><li>Finally, we export a checkPermission helper function that handles the common case of checking the current user&#39;s permissions. This function automatically retrieves the user context and throws an appropriate error if no user is found.</li></ul><h3>Implementing User Registration with Role-Based Authorization</h3><p>When users register for our e-learning portal, we need to establish their initial permissions and synchronize them with Permit.io.</p><p>Here’s how we handle user registration with proper authorization:</p><pre><br>export async function register(formData: FormData) {<br>  const supabase = createClient();<br>  const { email, password, fullName } = Object.fromEntries(formData);<br><br>  try {<br>    // Create the user account in Supabase<br>    const { data: { user }, error } = await supabase.auth.signUp({<br>      email,<br>      password,<br>      options: {<br>        data: { full_name: fullName }<br>      }<br>    });<br><br>    if (error) throw error;<br><br>    if (user) {<br>      // Create the user profile in our database<br>      await createProfile(user);<br><br>      // Set up initial permissions in Permit.io<br>      await syncUserWithPermit(user.id, user.email);<br>    }<br><br>    redirect(&#39;/auth/verify-email&#39;);<br>  } catch (error) {<br>    return { error: &#39;Registration failed&#39; };<br>  }<br>}</pre><h3>Managing Course Access with Permission-Based Controls</h3><p>The courses page demonstrates how to implement access control using our standardized checkPermission() method. This ensures consistent permission checking throughout our application:</p><pre><br>export default async function CoursesPage() {<br>  // Check various permissions the user might need<br>  const canViewAllCourses = await checkPermission(&#39;read&#39;, &#39;all-courses&#39;);<br>  const canViewOwnCourses = await checkPermission(&#39;read&#39;, &#39;own-courses&#39;);<br>  const canCreateCourse = await checkPermission(&#39;create&#39;, &#39;course&#39;);<br><br>  // Fetch courses based on permissions<br>  let courses;<br>  if (await checkPermission(&#39;read&#39;, &#39;all-courses&#39;)) {<br>    courses = await fetchAllCourses();<br>  } else if (await checkPermission(&#39;read&#39;, &#39;own-courses&#39;)) {<br>    courses = await fetchOwnCourses();<br>  } else {<br>    courses = await fetchEnrolledCourses();<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      {canCreateCourse &amp;&amp; &lt;CreateCourseButton /&gt;}<br>      &lt;CourseList <br>        courses={courses} <br>        permissions={{<br>          canEdit: await checkPermission(&#39;update&#39;, &#39;course&#39;),<br>          canDelete: await checkPermission(&#39;delete&#39;, &#39;course&#39;)<br>        }} <br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Securing API Routes with Standardized Permission Checks</h3><p>For API routes, we use the same checkPermission() method to maintain consistency in our authorization checks:</p><pre><br>export async function POST(req: NextRequest) {<br>  const user = await getUser();<br>  if (!user) {<br>    return NextResponse.json(<br>      { error: &#39;Not authenticated&#39; }, <br>      { status: 401 }<br>    );<br>  }<br><br>  try {<br>    // Use our standardized permission check<br>    const permitted = await checkPermission(&#39;create&#39;, &#39;course&#39;);<br><br>    if (!permitted) {<br>      return NextResponse.json(<br>        { error: &#39;Not authorized to perform this action&#39; }, <br>        { status: 403 }<br>      );<br>    }<br><br>    // Process the request after permission check passes<br>    const result = await processCourseCreation(req.body);<br>    return NextResponse.json(result);<br>  } catch (error) {<br>    console.error(&#39;Permission check failed:&#39;, error);<br>    return NextResponse.json(<br>      { error: &#39;Authorization check failed&#39; }, <br>      { status: 500 }<br>    );<br>  }<br>}</pre><h3>Creating a Permission-Based Component System</h3><p>We can create a reusable component that uses our checkPermission() method for consistent permission checking in our UI:</p><pre><br>interface WithPermissionProps {<br>  action: Actions;<br>  resource: Resources;<br>  fallback?: React.ReactNode;<br>}<br><br>export function WithPermission({<br>  action,<br>  resource,<br>  children,<br>  fallback = null<br>}: PropsWithChildren&lt;WithPermissionProps&gt;) {<br>  const [hasPermission, setHasPermission] = useState(false);<br><br>  useEffect(() =&gt; {<br>    async function verifyPermission() {<br>      try {<br>        const permitted = await checkPermission(action, resource);<br>        setHasPermission(permitted);<br>      } catch (error) {<br>        console.error(&#39;Permission check failed:&#39;, error);<br>        setHasPermission(false);<br>      }<br>    }<br>    verifyPermission();<br>  }, [action, resource]);<br><br>  return hasPermission ? children : fallback;<br>}</pre><p>Using this component makes permission-based rendering straightforward and consistent:</p><pre><br>function CourseActions({ courseId }: { courseId: string }) {<br>  return (<br>    &lt;div className=&quot;space-x-2&quot;&gt;<br>      &lt;WithPermission action=&quot;update&quot; resource=&quot;course&quot;&gt;<br>        &lt;EditCourseButton courseId={courseId} /&gt;<br>      &lt;/WithPermission&gt;<br>      <br>      &lt;WithPermission action=&quot;delete&quot; resource=&quot;course&quot;&gt;<br>        &lt;DeleteCourseButton courseId={courseId} /&gt;<br>      &lt;/WithPermission&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>And just like that, we have our e-learning portal built out!</p><h3>Conclusion</h3><p>In this tutorial, we’ve built a secure e-learning portal using Next.js and Permit.io that effectively manages different user roles and their access permissions. By centralizing our authorization logic through Permit.io’s RBAC system, we’ve created a maintainable solution that scales with your platform’s growth.</p><p>The combination of standardized permission checks, reusable components, and secure API endpoints ensures a robust foundation for managing courses, users, and enrollments.</p><p>As your e-learning portal grows, particularly with nested course structures and team hierarchies, scaling to <a href="https://www.permit.io/blog/what-is-rebac">ReBAC (Relationship-Based Access Control)</a> becomes valuable. ReBAC enables more sophisticated access patterns based on relationships between users, courses, and departments.</p><p>Ready to build your e-learning platform? <a href="https://github.com/ChisomUma/testpermit">Clone the repository</a> and explore <a href="https://docs.permit.io/?_gl=1*67utos*_gcl_au*NjM1NjE0MTA3LjE3MzU0MTA0NzA.*_ga*NjE4NjkxODA2LjE3MzU0MTA0NzA.*_ga_SPFKH5NXDE*MTczODUwNTYxOS40LjEuMTczODUwNTkyMC4wLjAuMA..">Permit.io’s documentation</a> to get started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95342ac977e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning vs. Machine Learning: Understanding the Difference]]></title>
            <link>https://medium.com/@chisomuma476/deep-learning-vs-machine-learning-understanding-the-difference-ba67316fc6e4?source=rss-77d4fc391b5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba67316fc6e4</guid>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Chisom Uma]]></dc:creator>
            <pubDate>Wed, 13 Mar 2024 18:59:10 GMT</pubDate>
            <atom:updated>2024-03-13T19:02:11.313Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6AY4Bb6JGUggC-a9" /><figcaption>Photo by <a href="https://unsplash.com/@davfts?utm_source=medium&amp;utm_medium=referral">David Pupăză</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Machine Learning (ML) and Deep Learning (DL) are two closely related fields in the realm of Artificial Intelligence (AI). While both aim to enable machines to learn from data and make predictions or decisions, there are significant differences between the two approaches. In this blog post, we’ll dive deep into the nuances of Deep Learning vs. Machine Learning, exploring their architectures, learning processes, and applications.</p><h3>What is Machine Learning?</h3><p>Machine Learning is a broad field of study that focuses on developing algorithms and statistical models that enable systems to perform specific tasks effectively without being explicitly programmed. In other words, ML algorithms learn from data, identify patterns, and make decisions or predictions based on those patterns.</p><p>The process of machine learning typically involves the following steps:</p><p>1. <strong>Data Collection:</strong> Relevant data is gathered from various sources, such as databases, sensors, or user interactions.<br>2. <strong>Data Preprocessing:</strong> The collected data is cleaned, formatted, and transformed into a suitable representation for the learning algorithm.<br>3.<strong> Feature Engineering:</strong> Relevant features are extracted or constructed from the preprocessed data to represent the input for the learning algorithm.<br>4. <strong>Model Training:</strong> The learning algorithm is trained on the prepared data, adjusting its internal parameters to optimize its performance on the given task.<br>5. <strong>Model Evaluation: </strong>The trained model is evaluated on a separate test dataset to measure its accuracy and performance.<br>6. <strong>Model Deployment:</strong> If the model performs satisfactorily, it can be deployed to make predictions or decisions on new, unseen data in a production environment.</p><p>Machine Learning algorithms can be broadly categorized into three main types: supervised learning, unsupervised learning, and reinforcement learning.</p><h3>What is Deep Learning?</h3><p>Deep Learning is a subset of Machine Learning inspired by the human brain&#39;s structure and function. It is based on artificial neural networks, which are multi-layered networks of interconnected nodes (or neurons) that can learn and make decisions from data.</p><p>The key distinguishing factor of Deep Learning is its ability to automatically learn and extract relevant features from raw data, eliminating the need for manual feature engineering. This is made possible by the hierarchical structure of deep neural networks, which consists of multiple layers of interconnected nodes that progressively extract higher-level features from the input data.</p><p>The learning process in Deep Learning involves the following steps:</p><p>1. <strong>Data Preparation:</strong> Raw data, such as images, text, or audio, is prepared and formatted for input into the neural network.<br>2. <strong>Network Architecture Design: </strong>The deep neural network architecture is designed, including the number of layers, types of layers (e.g., convolutional, recurrent), and connections between nodes.<br>3. <strong>Model Training:</strong> The neural network is trained on the prepared data using techniques like backpropagation and gradient descent optimization. During training, the network adjusts its internal parameters (weights and biases) to minimize the error between its predictions and the true labels or outputs.<br>4. <strong>Model Evaluation:</strong> The trained model is evaluated on a separate test dataset to measure its performance and generalization ability.<br>5. <strong>Model Deployment:</strong> If the model meets the desired performance criteria, it can be deployed in a production environment to make predictions or decisions on new, unseen data.</p><p>Deep Learning has proven to be particularly effective in domains such as computer vision, natural language processing, speech recognition, and recommendation systems, where the input data is high-dimensional and complex.</p><h3>Key Differences between Deep Learning and Machine Learning</h3><p>While Deep Learning is a subset of Machine Learning, there are several key differences between the two approaches:</p><p>1. <strong>Feature Engineering:</strong> In traditional Machine Learning, feature engineering plays a crucial role, as relevant features need to be manually extracted or constructed from the raw data. In Deep Learning, feature engineering is not required, as the neural networks can automatically learn and extract relevant features from the raw data.</p><p>2.<strong> Architecture:</strong> Machine Learning algorithms typically have a flat architecture, where the input features are directly mapped to the output. Deep Learning, on the other hand, employs a hierarchical architecture with multiple layers of interconnected nodes, allowing for the automatic extraction of increasingly complex features from the input data.</p><p>3. <strong>Data Representation: </strong>Machine Learning algorithms often require data to be represented in a tabular or structured format, with each row representing an instance and columns representing features. Deep Learning models can work directly with raw, unstructured data, such as images, text, or audio.</p><p>4. <strong>Performance on Complex Tasks:</strong> While Machine Learning algorithms can perform well on certain tasks, Deep Learning models have demonstrated superior performance on complex tasks involving high-dimensional data, such as image recognition, natural language processing, and speech recognition.</p><p>5. <strong>Computational Requirements:</strong> Deep Learning models typically require more computational resources (e.g., GPU acceleration) and larger amounts of training data compared to traditional Machine Learning algorithms, due to the complexity of the neural network architectures and the need for extensive training.</p><p>6. <strong>Interpretability:</strong> Machine Learning models, particularly those based on linear or tree-based algorithms, can be more interpretable, as their decision-making process can be traced back to the input features. Deep Learning models, with their hierarchical and highly non-linear nature, are often considered black boxes, making it challenging to interpret their internal representations and decision-making processes.</p><h3>Applications of Deep Learning and Machine Learning</h3><p>Both Deep Learning and Machine Learning have found widespread applications across various industries and domains. Here are some examples:</p><h4>Machine Learning Applications:</h4><p>- Fraud detection in financial transactions<br>- Predictive maintenance in manufacturing<br>- Recommendation systems (e.g., product recommendations, content suggestions)<br>- Spam filtering in email and messaging services<br>- Anomaly detection in cybersecurity and network monitoring<br>- Predictive analytics in healthcare and finance</p><h4>Deep Learning Applications:</h4><p>- Computer vision tasks, such as image recognition, object detection, and image segmentation<br>- Natural language processing tasks, such as text classification, machine translation, and sentiment analysis<br>- Speech recognition and synthesis<br>- Autonomous vehicles and robotics<br>- Generative models for creating new content (e.g., images, text, music)<br>- Reinforcement learning for decision-making in complex environments (e.g., game playing, control systems)</p><p>While Deep Learning has gained significant attention and achieved remarkable success in many complex domains, traditional Machine Learning algorithms continue to be widely used and effective in various applications, particularly those involving structured data and simpler tasks.</p><h3><strong>Conclusion</strong></h3><p>Both Machine Learning and Deep Learning are powerful tools in the field of Artificial Intelligence, each with its own strengths and applications. While Machine Learning algorithms excel at structured data and simpler tasks, Deep Learning models have demonstrated superior performance on complex tasks involving high-dimensional, unstructured data.</p><p>As technology continues to evolve, we can expect to see further advancements and convergence between these two fields, with the potential for hybrid approaches that combine the strengths of both Machine Learning and Deep Learning. Ultimately, the choice between these two approaches will depend on the specific problem at hand, the available data, and the desired performance and interpretability requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba67316fc6e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interacting with Smart Contracts using Web3]]></title>
            <link>https://medium.com/stackanatomy/interacting-with-smart-contracts-using-web3-83aeb98644e6?source=rss-77d4fc391b5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/83aeb98644e6</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[webdev]]></category>
            <dc:creator><![CDATA[Chisom Uma]]></dc:creator>
            <pubDate>Mon, 27 Jun 2022 11:22:25 GMT</pubDate>
            <atom:updated>2022-07-01T10:27:16.523Z</atom:updated>
            <content:encoded><![CDATA[<p>by <a href="https://blog.openreplay.com/authors/chisom-uma">Chisom Uma</a></p><p>Web3.js is a collection of libraries that make it easier to interact with the <a href="https://www.blockchain.com/learning-portal/ether-basics">Ethereum blockchain</a>. For example, it can be used to check if a given string is a valid Ethereum address, retrieve user accounts, send transactions, and make interacting with contracts much easier. In this article, we will look at how you can interact with the blockchain from your React web application using <a href="https://web3js.readthedocs.io/en/v1.7.3/">Web3.js</a>, a library that lets you interact with the blockchain efficiently.</p><h3>Creating our React app</h3><p>Creating a React app project is pretty straightforward. All you have to do is go into your terminal and type in the following command:</p><pre>npx create-react-app my-web3</pre><p>Go into your device folder and open the newly created React app project on your code editor. Then, open your App.js file in your directory and edit the code to look like this.</p><pre>import React, {useEffect} from &#39;react&#39;;<br>import Web3 from &#39;web3&#39;<br><br>function App() {<br>  useEffect(() =&gt; {<br><br>}, []);<br>  return &lt;div className=&#39;App&#39;&gt;&lt;/div&gt;;<br>}<br>export default App;</pre><p>Then go ahead and run the following command in your terminal, to install Web3.</p><pre>npm install web3 --save</pre><h3>Ethereum nodes and providers</h3><p>Let’s look at how you can pass in a provider URL, which will be a link to your Ethereum node.</p><pre>function App() {<br>  const providerUrl = process.env.PROVIDER_URL;<br><br>  useEffect(() =&gt; {<br>    const web3 = new Web3(providerUrl)<br>}, []);<br>  return &lt;div className=&#39;App&#39;&gt;&lt;/div&gt;;</pre><p>This node is your gateway to the rest of the network. But not to worry, you won’t need to set up your own node and host it on something like AWS. Luckily, there are many services, such as <a href="https://infura.io/">Infura</a> or <a href="https://www.alchemy.com/">Alchemy</a>, that already do all that. All you need is a link from them, to paste in providerUrl.</p><h3>Deploying Smart Contracts to Blockchain</h3><p>For this article, you will have your own smart contract that you will deploy using <a href="https://trufflesuite.com/docs/truffle/">Truffle</a>. In this tutorial, we have a straightforward <a href="https://en.wikipedia.org/wiki/Non-fungible_token">NFT</a> smart contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*hHNHclE1nCK8I3Ii.png" /></figure><p>This will be deployed to the local <a href="https://trufflesuite.com/docs/ganache/">Ganache</a> instance, a local blockchain that you can use for testing purposes. So, go to your terminal and run this command:</p><pre>npx ganache-cli</pre><p>Once you run the command, you should be able to see something like this on your terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*tsOLC3To891e9N8H.png" /></figure><p>Now let’s deploy the contract. To do this, go to your terminal and run these commands, so Truffle will compile the contracts.</p><pre>truffle init<br>npx truffle migrate</pre><h3>How the user interacts with your dApp</h3><p>The thing with <a href="https://www.techtarget.com/iotagenda/definition/blockchain-dApp">dApps</a> (decentralized applications) is that your users will need a wallet to sign the transactions, and the most popular wallet of all is, of course, <a href="https://metamask.io/">Metamask</a>. If your users are already familiar with crypto and the blockchain space, they probably already have installed Metamask as a Chrome extension. To follow this tutorial, you should also have it installed. (If your users are unfamiliar with crypto and blockchain, they can use other services such as <a href="https://fortmatic.com/">Fortmatic</a>; they will give your users a wallet without installing anything.) In this article, I will only be showing you how to integrate Metamask, but steps for other wallets should be pretty similar.</p><p>Metamask injects itself into the browser, so when you make any transactions or calls, you will be dealing with Metamask itself, not with your provider. Metamask also uses Infura in the background, but you will not be interacting directly with them, and you will be dealing with Metamask or the wallet service you are using. We are going to look at how we can integrate Metamask. If you haven’t already done so, you can download the Metamask extension <a href="https://metamask.io/download/">here</a>.</p><pre>useEffect(() =&gt; {<br>  const web3 = new Web3(providerUrl)  <br><br>  let provider = window.ethereum;<br><br>  if (typeof provider !== &#39;undefined&#39;) {<br>      //Metamask is installed<br>  provider<br>  .request({method: &#39;eth_requestAccounts&#39; })<br>  .then((accounts) =&gt; {<br>    console.log(accounts);<br>  })<br>  .catch((err) =&gt; {<br>    console.log(err);<br>  });<br>  }<br>}, []);</pre><p>Here we check if Metamask is installed using let provider = window.ethereum;. We then asked the user to connect their <a href="https://www.investopedia.com/terms/b/bitcoin-wallet.asp">wallet</a> to the website by sending a .request to the provider to gain access to the user&#39;s account. If you save and run this using the npm start command, you should be able to get something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*kxaJ0zd2QNoHD8aS.gif" /></figure><p>You can also listen to Metamask account changes by adding an event listener.</p><pre>provider<br>    .request({method: &#39;eth_requestAccounts&#39; })<br>    .then((accounts) =&gt; {<br>      console.log(accounts);<br>    })<br>    .catch((err) =&gt; {<br>      console.log(err);<br>    });<br>    window.ethereum.on(&#39;accountsChanged&#39;, function (accounts) {<br>      console.log(accounts);<br>    });<br>    }<br>    const web3 = new Web3(provider);<br>  }, []);</pre><p>Once you save this, go to your browser console and open your Metamask. Change your wallet account, and you should be able to see that there is another output on the console, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*QyMrO0iuCPSjYg9G5WCnzA.gif" /></figure><p>So, with a few lines of code, we have linked Metamask and can now start interacting with smart contracts. But first, we need to do some tidying up because this code isn’t very reusable. So, we create a new file in our src folder titled Web3Client.js and edit it to look like this.</p><pre>import Web3 from ‘web3’</pre><pre>let selectedAccount;</pre><pre>export const init = () =&gt; {<br>let provider = window.ethereum;</pre><pre>if (typeof provider !== &#39;undefined&#39;) {</pre><pre>provider<br>.request({method: &#39;eth_requestAccounts&#39; })<br>.then((accounts) =&gt; {<br>  selectedAccount = accounts[0];<br>  console.log(`Selected account is ${selectedAccount}`);<br>})<br>.catch((err) =&gt; {<br>  console.log(err);<br>});<br>window.ethereum.on(&#39;accountsChanged&#39;, function (accounts){<br>  selectedAccount = accounts[0];<br>  console.log(`Selected account changed to ${selectedAccount}`);<br>});</pre><pre>}<br>const web3 = new Web3(provider);<br>};</pre><p>Then edit the App.js file to look like this.</p><pre>import React, { useEffect } from ‘react’;<br>import {init} from ‘./Web3Client’;</pre><pre>function App() {</pre><pre>useEffect(() =&gt; {<br>init();<br>}, []);</pre><pre>return &lt;div className=&#39;App&#39;&gt;&lt;/div&gt;</pre><pre>}<br>export default App;</pre><p>Rerun the code, and you will still get the same results.</p><h3>Adding a Smart Contract to your Web app</h3><p>We will now look at how we can define the <a href="https://www.investopedia.com/terms/s/smart-contracts.asp#:~:text=A%20smart%20contract%20is%20a,a%20distributed%2C%20decentralized%20blockchain%20network.">smart contract</a>.</p><pre>import Web3 from &#39;web3&#39;<br>import NFTContractBuild from &#39;../truffle/build/contracts/NFT.json&#39;;<br>let selectedAccount;</pre><pre>export const init = async () =&gt; {<br>    let provider = window.ethereum;</pre><pre>if (typeof provider !== &#39;undefined&#39;) {<br>    <br>    provider<br>    .request({method: &#39;eth_requestAccounts&#39; })<br>    .then((accounts) =&gt; {<br>      selectedAccount = accounts[0];<br>      console.log(`Selected account is ${selectedAccount}`);<br>    })<br>    .catch((err) =&gt; {<br>      console.log(err);<br>    });<br>    window.ethereum.on(&#39;accountsChanged&#39;, function (accounts){<br>      selectedAccount = accounts[0];<br>      console.log(`Selected account changed to ${selectedAccount}`);<br>    });<br>  }<br>  const web3 = new Web3(provider);<br>  const networkId = await web3.eth.net.getId();<br>  const nftContract = new web3.eth.Contract(NFTContractBuild.abi,NFTContractBuild.networks[networkId].address<br>  );<br>};</pre><p>You will probably get this error when you try to run this code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*9ueUYoHhIuIDUwWkA1Wuig.png" /></figure><p>If you used the create-react-app to create your own application, then all you need to do is go into your dependencies for React, and add a new dependency, as shown in the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*kfNEYi4UZLRMf98J4v9zKg.png" /></figure><p>As you can see, &quot;contracts&quot;: &quot;file:./truffle/build/contracts&quot; was added to the dependencies. Next, enter the command `npm i’ to install the dependency. Now we can do different things with the NFT contract. For this article, we will only use the smart contract to make a transaction (mint a token).</p><h3>Making a transaction</h3><p>Let’s take a look at how we can make a transaction.</p><pre>import Web3 from &#39;web3&#39;<br>import NFTContractBuild from &#39;../truffle/build/contracts/NFT.json&#39;;</pre><pre>let selectedAccount;<br>let nftContract;<br>let isInitialized = false;</pre><pre>export const init = async () =&gt; {<br>    let provider = window.ethereum;</pre><pre>if (typeof provider !== &#39;undefined&#39;) {<br>    <br>    provider<br>    .request({method: &#39;eth_requestAccounts&#39; })<br>    .then((accounts) =&gt; {<br>      selectedAccount = accounts[0];<br>      console.log(`Selected account is ${selectedAccount}`);<br>    })<br>    .catch((err) =&gt; {<br>      console.log(err);<br>      return;<br>    });<br>    window.ethereum.on(&#39;accountsChanged&#39;, function (accounts){<br>      selectedAccount = accounts[0];<br>      console.log(`Selected account changed to ${selectedAccount}`);<br>    });<br>  }<br>  const web3 = new Web3(provider);<br>  const networkId = await web3.eth.net.getId();<br>  nftContract = new web3.eth.Contract(NFTContractBuild.abi,NFTContractBuild.networks[networkId].address<br>  );<br>  isInitialized = true;<br>};</pre><pre>export const mintToken async = () =&gt; {<br>  if (!isInitialized) {<br>    await init();<br>}<br>  return nftContract.methods<br>    .mint(selectedAccount)<br>    .send({from: selectedAccount})<br>}</pre><p>Here, what we did is <a href="https://corporatefinanceinstitute.com/resources/knowledge/data-analysis/minting-crypto/">mint</a> a new token. Now, let’s go back into our App.js component and make more changes.</p><pre>import React, { useEffect } from &#39;react&#39;;<br>import {init, mintToken} from &#39;./Web3Client&#39;;</pre><pre>function App() {<br>  const [minted, setMinted] = useState(false);<br>  const mint = () =&gt; {<br>    mintToken().then(tx =&gt; {<br>    console.log(tx);<br>    setMinted(true);<br>    }).catch(err =&gt; {<br>    console.log(err);<br>    });<br>}<br>  return &lt;div className=&#39;App&#39;&gt;<br>    {!minted ? (<br>        &lt;button onClick={() =&gt; mint()}&gt;Mint Token&lt;/button&gt;<br>        ):(<br>        &lt;p&gt;Token minted successfully!&lt;/p&gt;<br>        )}<br>        &lt;/div&gt;<br>      );<br>}<br>export default App;</pre><p>We created a button that says “Mint token” if no token is minted, then a paragraph that says “Token minted successfully” if a token is already minted. Then we imported mintToken from our ./Web3Client file. We also setMinted to true. Once you rerun the code, click on Mint token, and you should see something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*VRXNNoEDXIe-s3rTFE4zgg.png" /></figure><p>Metamask will now pop up and ask us to approve and send the transaction. However, we do not have any <a href="https://ethereum.org/en/eth/">ether</a> to pay the <a href="https://www.investopedia.com/terms/g/gas-ethereum.asp">gas fee</a>. So, let’s go back to our terminal, run the npx ganache-cli command again, and find and copy the private key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*3eX_9kxqQY7-3ufdWlWe3A.png" /></figure><p>Head back to your Metamask, click on Import Account, and paste.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*Hcm8gSfew31VJqvRqHFmPA.png" /></figure><p>Click on import.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*GZRfT4_Ak_Mp-rr5Kvj2kQ.png" /></figure><p>You should now be able to see this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*9cKj09Ew_9UDwfNkMaaOvA.png" /></figure><p>Note that this is not real Ethereum, and it appears this way because when you run the ganache command, it will automatically generate some ether, 100 by default. Click on confirm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*_OgfPJ5zJ8fmwIkvU8n6qA.png" /></figure><p>You should see this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*iZuPQKhU1aKU1UinDuAmHg.png" /></figure><p>So, that’s it!</p><p><em>Originally published at </em><a href="https://blog.openreplay.com/interacting-with-smart-contracts-using-web3"><em>blog.openreplay.com</em></a><em> on June 27, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83aeb98644e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stackanatomy/interacting-with-smart-contracts-using-web3-83aeb98644e6">Interacting with Smart Contracts using Web3</a> was originally published in <a href="https://medium.com/stackanatomy">StackAnatomy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web3 Authentication with Next.js, React, and Moralis]]></title>
            <link>https://medium.com/stackanatomy/web3-authentication-with-next-js-react-and-moralis-4f7e2a6f640b?source=rss-77d4fc391b5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f7e2a6f640b</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Chisom Uma]]></dc:creator>
            <pubDate>Thu, 02 Jun 2022 12:03:22 GMT</pubDate>
            <atom:updated>2022-06-26T21:25:12.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_HNsfiWSITbAWTg3LcFpjQ.png" /></figure><p>by <a href="https://blog.openreplay.com/authors/chisom-uma">Chisom Uma</a></p><p>Authentication is essential in providing services to valid users, and it is often accomplished using login and password. User credentials such as passwords, smart cards, token devices, and biometrics can be used to prove one’s identity. In this article, we will be building a Web3 login page using Next, React, and Moralis. You’ll need to have both Node.js and Next.js (version 12) installed on your machine.</p><h3>What is Moralis, and why should you use it?</h3><p>If you are new to Web3 or blockchain and read this article, you probably wonder what Moralis is. Well, <a href="https://moralis.io/">Moralis</a> is a piece of software that allows you to build cross-chain <a href="https://www.investopedia.com/terms/d/decentralized-applications-dapps.asp">dApps</a> (decentralized applications) very quickly.</p><p>Moralis offers a single workflow for developing high-performance dApps. Your preferred web3 tools and services are fully compatible with Moralis. There are several good facts about it:</p><ul><li>Moralis is the quickest way to create and deploy decentralized applications (dApps) on Ethereum, BSC, Polygon, Solana, Elrond, etc.</li><li>By default, all Moralis dApps are <a href="https://www.blockchain-council.org/blockchain/blockchain-interoperability/">cross-chain</a>. Moralis ensures that your dApp will be future-proof. Your dApp will work on any chain, even if additional blockchains are created.</li><li>Moralis makes it easier to establish, maintain, and grow your blockchain applications, whether you’re a beginner or an experienced developer.</li></ul><h3>Setting up the Next project</h3><p>According to the official <a href="https://nextjs.org/learn/foundations/about-nextjs/what-is-nextjs">Next Docs</a>, <em>Next.js is a flexible React framework that gives you building blocks to create fast web applications.</em></p><p>The first thing you need to do is to go to your terminal and create a Next app using the command below:</p><pre>npx create-next-app@latest</pre><p>Once you run this command, you will be asked, “what is your project name?”. You can name it whatever you want, but let’s just name it “Sign-In” for this article. The @latest at the end of the command allows you to get the latest version of Next installed: currently, version 12.</p><p>This is what your Next directory should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/0*aClcfmyHcLkMUAla.png" /></figure><p>How Next.js works is that public is for public icons, and pages is where all the pages are held.</p><h3>Building the Front-End</h3><p>In this article, we will build a beautiful Login page with Moralis, that connects to the <a href="https://metamask.io/">Metamask</a> wallet whenever you click the sign-up button. First, edit your index.js file to look like this:</p><pre>export default function Home() {<br>  return <br>    &lt;div&gt;&lt;/div&gt;<br>}</pre><p>Then, go to your styles &gt; globals.css file, and edit it to look like this:</p><pre>html,<br>body {<br>  padding: 0;<br>  margin: 0;<br>  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,<br>    Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;<br>}<br>a {<br>  color: inherit;<br>  text-decoration: none;<br>}<br>* {<br>  box-sizing: border-box;<br>  margin: 0px;<br>}</pre><p>The only thing we did here was adding a margin of 0px at the bottom of the globals.css.</p><p>Next, create another folder called components by clicking on the folder symbol at the top of your directory. Anything that is not a page should be in components because we do not want to mix things up. Then, create a new component inside that folder, and name it Login.js.</p><p>We also created an images folder to house our Moralis icon, which you can get from my Github attached at the end of this article. This is what your directory should now look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/0*AejJhCme26p_Q3Ix.png" /></figure><p>The next step is to edit your index.js file to now look like this:</p><pre>import Login from &quot;../components/Login&quot;;<br><br>export default function Home() {<br>  return (<br>    &lt;div&gt;<br>      &lt;Login /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>To build out the visuals for our Login page, we have to go over the styles and create a new file called Login.module.css. This is where we will be writing most of our CSS, and it should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*nPiI3FcAreEcE1jl.png" /></figure><p>Now, go to the Login.js file and edit the code to look like this:</p><pre>import styles from &quot;../styles/Login.module.css&quot;;<br>import Image from &quot;next/image&quot;;<br>import icon from &quot;./Images/Moralis-Favicon.svg&quot;;<br><br>function Login() {<br><br>    return (<br>      &lt;div className={styles.login_container}&gt;<br>        &lt;div className={styles.login_card}&gt;<br>          &lt;Image src={icon} width={100} height={100}/&gt;<br>          &lt;div className={styles.sign_in_container}&gt;<br>          &lt;button&gt;Login with Moralis&lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>}<br><br>export default Login;</pre><p>Here, we import styles from Login.module.css; then, we create the div and className, which we use to style our Login page in the Login.module.css file.</p><p>Next, go into your Login.module.css and input the following css code:</p><pre>.login_container {<br>    background-color: rgb(14 165 233);<br>    height: 100vh;<br>    display: grid;<br>    align-items: center;<br>    justify-content: center;<br>}<br>.login_card{<br>    background-color: white;<br>    width: 200px;<br>    height: 250px;<br>    border-radius: 40px;<br>    display: flex;<br>    flex-direction: column;<br>}<br>.sign_in_container{<br>    flex: 1;<br>    display: flex;<br>    flex-direction: column;<br>    align-items: center;<br>    justify-content: center;<br>}<br>.sign_in_container &gt; button {<br>    padding: 10px;<br>    border: none;<br>    border-radius: 40px;<br>    background-color: rgb(14 165 233);<br>    color: white;<br>}</pre><p>After doing this, run the code using the npm run dev command, and you should be able to see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*xXXMGSGkfWceqgRP.png" /></figure><p>The next step is combining this with Moralis Login.</p><h3>Open Source Session Replay</h3><p><a href="https://github.com/openreplay/openreplay"><em>OpenReplay</em></a><em> is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*QLjOCxDiW7wgSBZT.png" /></figure><p><em>Start enjoying your debugging experience — </em><a href="https://github.com/openreplay/openreplay"><em>start using OpenReplay for free</em></a><em>.</em></p><h3>Setting up Moralis</h3><p>The first thing you need to do here is going to your editor’s terminal and install Moralis SDK for React. To do this, you need to run the following commands:</p><pre>npm install moralis --save<br>npm install react-moralis --save</pre><p>Now rerun the program using npm run dev; everything should still work.</p><p>The next thing is to create a Moralis server. If you do not already know how to do this, follow the steps below.</p><p>First, click <a href="https://moralis.io/">here</a> to access Moralis’ official website. It should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/0*WYtq31kxkJLxNfDB.png" /></figure><p>The next step is to create an account and log in to your admin dashboard. Your dashboard should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*05vtqJua5wHLaGH1.png" /></figure><p>You should then click on “create a new server” and “Local Devchain Server” because this isn’t a <a href="https://academy.binance.com/en/glossary/mainnet">Mainnet</a> or <a href="https://en.wikipedia.org/wiki/Testnet">Testnet</a>. You should now see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/0*ZnLvxlUvy9UpC1mk.png" /></figure><p>Now put in whatever name you want to give your server. Select your region (if you did not see your region, you might just put in any region closest to you), then click Eth (LocalDevChain), and finally, click “Add Instance”. You should now see this on your dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*RdeRsVkRYNfMSND8.png" /></figure><p>Click on view details, and you should now see this pop up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/0*NOi4ygQqM3o4lvlm.png" /></figure><p>We are done! Now, let’s look at integrating it into our software.</p><h3>Integrate Moralis</h3><p>For this to work, go into your App.js file, which is the file that renders your whole component in Next.js, and edit your code to be like this:</p><pre>import &#39;../styles/globals.css&#39;<br>import {MoralisProvider} from &quot;react-moralis&quot;<br>function MyApp({Component, pageProps}) {<br>  return(<br><br>    &lt;MoralisProvider <br>    appId=&#39;6lBD71Mo22ez4lirpwGrJCUsiIo3mnICTRRzTumY&#39; <br>    serverUrl=&#39;https://jp1q6eia3n4c.usemoralis.com:2053/server&#39;&gt;<br>      {<br>        &lt;Component {...pageProps} /&gt;<br>      }<br>    &lt;/MoralisProvider&gt;<br>    );<br>  }<br><br>export default MyApp</pre><p>Here, we wrapped the whole component with MoralisProvider . MoralisProvider takes in the arguments of appId and severUrl, as you can see in the code above. You should copy the appId and serverUrl from your generated Moralis server and paste them into your App.js file. To implement user authentication, edit your Login.js file to look like this.</p><pre>import styles from &quot;../styles/Login.module.css&quot;;<br>import Image from &quot;next/image&quot;;<br>import icon from &quot;./Images/Moralis-Favicon.svg&quot;;<br>import {useMoralis}from &quot;react-moralis&quot;;<br><br>function Login() {<br>    const {authenticate, authError} = useMoralis();<br>    return (<br>      &lt;div className={styles.login_container}&gt;<br>        &lt;div className={styles.login_card}&gt;<br>          &lt;Image src={icon} width={100} height={100}/&gt;<br>          &lt;div className={styles.sign_in_container}&gt;<br>          &lt;button onClick={authenticate}&gt;Login with Moralis&lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt; <br>      &lt;/div&gt;<br>    );<br>}<br>export default Login;</pre><p>After that, go to your terminal and run the following command:</p><pre>npm i magic-sdk --save<br>npm i @walletconnect/web3-provider --save<br>npm i @web3auth/web3auth --save</pre><p>The next and most important step is to install the <a href="https://metamask.io/download/">Metamask extension</a> on your browser. Once you run the code, you should be able to get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*3WQiiyy8exMBcoQ-.gif" /></figure><h3>Error Handling</h3><p>Let’s say there is an error with the app, and you want it to be displayed on the Login page. To do this, you have to edit your Login.js file like this:</p><pre>import styles from &quot;../styles/Login.module.css&quot;;<br>import Image from &quot;next/image&quot;;<br>import icon from &quot;./Images/Moralis-Favicon.svg&quot;;<br>import {useMoralis} from &quot;react-moralis&quot;;<br><br>function Login() {<br>    const {authenticate, authError} = useMoralis();<br>    return (<br>      &lt;div className={styles.login_container}&gt;<br>        &lt;div className={styles.login_card}&gt;<br>          &lt;Image src={icon} width={100} height={100}/&gt;<br>          &lt;div className={styles.sign_in_container}&gt;        <br>            {authError &amp;&amp; (<br>              &lt;p className={styles.error}&gt;<br>                {authError.name}<br>                {authError.message}<br>              &lt;/p&gt;<br>            )}<br>            &lt;button onClick={authenticate}&gt;Login with Moralis&lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>}<br>export default Login;</pre><p>To make the error messages look nicer, go to your Login.module.css file and add the following css code as the last part of the code:</p><pre>.error{<br>    color: red;<br>    text-align: center;<br>    font-size: 10px;<br>    font-style:italic;<br>    margin: 5px;<br>}</pre><p>Whenever you get an error, it should appear like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/0*utRYAq7-jjYHIsH3.png" /></figure><p>Pretty cool, right?</p><h3>Logout</h3><p>Now, let’s say a user is logged in and wants to log out. To do this, go to your index.js file and edit it to look like this:</p><pre>import Login from &quot;../components/Login&quot;;<br>import {useMoralis} from &quot;react-moralis&quot;;<br><br>export default function Home() {<br>  const {isAuthenticated, logout} = useMoralis();<br>  return &lt;div&gt;{isAuthenticated ? (<br>  &lt;p&gt;<br>    You are logged in<br>    &lt;button onClick= {logout}&gt;Sign Out&lt;/button&gt;<br>  &lt;/p&gt;<br>    ):(<br>    &lt;Login/&gt;<br>  )}<br><br>  &lt;/div&gt;;<br>}</pre><p>Once this is implemented and you run the code, you should get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*5EHmakLZqUL7bjbj.gif" /></figure><p>That’s it! We are done building our Web3 Login webpage.</p><h3>Conclusion</h3><p>This article taught us how to build a beautiful Web3 Login webpage using Next.js, React, and Moralis. Hopefully, you learned more than just using Moralis, but also how to build beautiful web pages.</p><p>Here is the link to my <a href="https://github.com/ChisomUma/Web3">Github</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*s_LDfqoR9TLAGzlT.png" /></figure><p><em>Originally published at </em><a href="https://blog.openreplay.com/web3-authentication-with-next-js-react-and-moralis"><em>blog.openreplay.com</em></a><em> on June 2, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f7e2a6f640b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stackanatomy/web3-authentication-with-next-js-react-and-moralis-4f7e2a6f640b">Web3 Authentication with Next.js, React, and Moralis</a> was originally published in <a href="https://medium.com/stackanatomy">StackAnatomy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Command-Line Apps Using React Ink]]></title>
            <link>https://medium.com/stackanatomy/building-command-line-apps-using-react-ink-df090dc6c60b?source=rss-77d4fc391b5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/df090dc6c60b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ink]]></category>
            <dc:creator><![CDATA[Chisom Uma]]></dc:creator>
            <pubDate>Fri, 06 May 2022 11:46:00 GMT</pubDate>
            <atom:updated>2022-05-21T22:41:22.055Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SR2JvsXJCxnhN3tN3W4lFg.png" /></figure><p>by <a href="https://blog.openreplay.com/authors/chisom-uma">Chisom Uma</a></p><p>Command-Line Apps (CLI: Command Line Interface) are programs you can interact with through your terminal, without graphics or visual interface that do not go beyond what you see in your terminal. Recent command-line apps accept user input, provide attractive command-line user interfaces, and can handle even the most complex jobs, such as leading the user through various process phases. As the usefulness of command-line interfaces improves, they become available for an increasing number of tasks. Modern CLIs are already replacing some GUIs (graphical user interfaces).</p><p>React Ink is a framework that provides the same component-based UI building experience that React offers in the browser but for command-line apps. It uses <a href="https://github.com/facebook/yoga">Yoga</a> to build Flexbox layouts in the terminal. In this article, you will learn how to build and implement command-line apps using <a href="https://github.com/vadimdemedes/ink">React Ink</a>. You should have Node.Js installed on your device to follow this article.</p><h3>Creating an Ink Project</h3><p>Creating or scaffolding a new Ink project is pretty straightforward. The first thing you need to do is go to your terminal and create a new project folder using the following command.</p><pre>mkdir react-ink &amp; cd react-ink</pre><p>You then need to run the script using the npx command, which is already installed together with node.js.</p><pre>npx create-ink-app</pre><p>Once everything is finished installing, it should look like this when you open the project on your code editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/0*r2ZQaep6ebKToK5Q.png" /></figure><p>Let us look at one of the JavaScript files, the ui.js file that is the main entry point for the implementation of the command line user interface:</p><pre>&quot;use strict&quot;;<br>const React = require(&quot;react&quot;);<br>const { Text } = require(&quot;ink&quot;);<br><br>const App = ({ name = &quot;Stranger&quot; }) =&gt; (<br>  &lt;Text&gt;<br>    Hello, &lt;Text color=&quot;green&quot;&gt;{name}&lt;/Text&gt;<br>  &lt;/Text&gt;<br>);<br><br>module.exports = App;</pre><p><strong>Note:</strong> Once you install React Ink and open the ui.js file, you will automatically see the exact code above. In React Ink, imports are made using require, while exports are made using module.exports.</p><p>The file above will look familiar if you already have some experience with React. This is the default implementation of the default CLI, which appears when scaffolding a new project with React Ink. Now, let us try things out and see what happens in the terminal. To run the code, you will have to type in node cli.js on your terminal, and you will get this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/0*MJpD368uHu4Rrny-.png" /></figure><p>This command also provides help when you type in the command node cli.js --&quot;help. After running this command, you should be able to get this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/0*IU0Bc-Fsh2qqm6kb.png" /></figure><p>The output, as seen above, gives us instructions on the usage of the CLI. Now, let’s try out the command as seen above, but we will supply a value for the name parameter and change the output this time. Ignore the react-ink command shown above. You can still try the app out by replacing node cli.js with react-ink and use it from the beginning of this article. If it does not work, use node cli.js as I am using in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/0*W163QnAWv9Q9yU5S.png" /></figure><p>Now, let’s say we want to add another command line parameter which can be used as another option to supply another value to our command-line interface, we can do that as shown in the example below:</p><pre>&quot;use strict&quot;;<br>const React = require(&quot;react&quot;);<br>const { Text } = require(&quot;ink&quot;);<br><br>const App = ({ name = &quot;Stranger&quot;, from = &quot;London&quot; }) =&gt; (<br>  &lt;Text&gt;<br>    Hello,{&quot;&quot;}<br>    &lt;Text color=&quot;green&quot;&gt;<br>      {name} from {from}<br>    &lt;/Text&gt;<br>  &lt;/Text&gt;<br>);<br><br>module.exports = App;</pre><p>Now, go to your terminal again and try out the node cli.js command without any parameters because we have already set a default value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/0*oFvECwu7NKIGa46D.png" /></figure><p>Let’s say we want to use the name attribute and add in a value using from. You can do it like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*xPexfW0cW3pALwUn.png" /></figure><p>Pretty simple, right?</p><p>This next example is an implementation of a command-line interface, which uses another Ink layout component (the box component). We will see how we can change the output by using some other Ink components, and how easy it is for us to structure our output by using those components:</p><pre>&quot;use strict&quot;;<br>const React = require(&quot;react&quot;);<br>const { Text, Box } = require(&quot;ink&quot;);<br><br>const App = ({ name = &quot;Stranger&quot;, from = &quot;London&quot; }) =&gt; (<br>  &lt;Box borderStyle=&quot;round&quot; borderColor=&quot;yellow&quot;&gt;<br>    &lt;Text&gt;<br>      Hello,{&quot;&quot;}<br>      &lt;Text color=&quot;green&quot;&gt;<br>        {name} from {from}<br>      &lt;/Text&gt;<br>    &lt;/Text&gt;<br>  &lt;/Box&gt;<br>);<br><br>module.exports = App;</pre><p>Now, you get something like this when you move over to your terminal and input the command node cli.js --name Chisom --from France again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/0*qvAaGq8WBYSXU7J2.png" /></figure><p>We surrounded the text element with the Box component, and we added a borderStyle and borderColor.</p><h3>Open Source Session Replay</h3><p><a href="https://github.com/openreplay/openreplay"><em>OpenReplay</em></a><em> is an open-source alternative to FullStory and LogRocket. It gives you full observability by replaying everything your users do on your app and showing how your stack behaves for every issue. OpenReplay is self-hosted for full control over your data.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*rcaLawlpiqLR1D3-.png" /></figure><p><em>Happy debugging for modern frontend teams — </em><a href="https://github.com/openreplay/openreplay"><em>start monitoring your web app for free</em></a><em>.</em></p><h3>Building a Country Command-Line App</h3><p>Now that you have an idea of how command-line apps can be built and displayed on your terminal, let us build a more complex project. We’ll create a Country CLI that allows a user to input a country and get the country’s capital and currency in a table. This project will help you understand React Ink’s elements and project structure, so, let’s get started.</p><p>First, your ui.js file should be in the default form, as it is when React Ink is installed using the npx command, as i already showed you at the beginning of this article. So, it should look like this:</p><pre>&quot;use strict&quot;;<br>const React = require(&quot;react&quot;);<br>const { Text } = require(&quot;ink&quot;);<br><br>const App = ({ name = &quot;Stranger&quot; }) =&gt; (<br>  &lt;Text&gt;<br>    Hello, &lt;Text color=&quot;green&quot;&gt;{name}&lt;/Text&gt;<br>  &lt;/Text&gt;<br>);<br><br>module.exports = App;</pre><p>To build this project, we need to install an npm package known as <a href="https://www.npmjs.com/package/world-countries-capitals">world-countries-capitals</a>. But first, let us get the user input by running this command in the terminal.</p><pre>npm install ink-text-input</pre><p>We import and use the text input in the terminal, in our ui.js. To store our country value and handle changes to the country name, we&#39;ll utilize the useState hooks. UseState hooks can be seen as a mechanism to work with variables in React. Check out the <a href="https://reactjs.org/docs/hooks-overview.html">React documentation</a> to learn more about React hooks. <br> The code on your ui.js file should now look like this:</p><pre>&quot;use strict&quot;;<br>const React = require(&quot;react&quot;);<br>const { Box } = require(&quot;ink&quot;);<br>const TextInput = require(&quot;ink-text-input&quot;).default;<br><br>const App = () =&gt; {<br>  const [country, setCountry] = React.useState(&quot;&quot;);<br><br>  return (<br>    &lt;Box&gt;<br>      &lt;TextInput<br>        placeholder=&quot;Enter country...&quot;<br>        value={country}<br>        onChange={setCountry}<br>      /&gt;<br>    &lt;/Box&gt;<br>  );<br>};<br><br>module.exports = App;</pre><p>Now, we need to be able to search for the country in real-time and display the results in a table. To do this, we need to install the world-countries-capitals npm package. We will also use the useEffect hook to fetch our required data and update the component as it renders. Go to your terminal and install the package:</p><pre>npm install world-countries-capitals</pre><p>At the top of our ui.js file, we import the package:</p><pre>const wcc = require(&quot;world-countries-capitals&quot;);</pre><p>Next, we need to create some variables that will hold the data we get from the useEffect hook, using useState.</p><pre>const [capital, setCapital] = React.useState(&quot;&quot;);<br>const [currency, setCurrency] = React.useState(&quot;&quot;);<br>const [phone, setPhone] = React.useState(&quot;&quot;);</pre><p>We need to update our variables with the information from the npm package. The complete useEffect hook should look like the code below.</p><pre>React.useEffect(() =&gt; {<br>  const getCountry = wcc.getCountryDetailsByName(country);<br>  setCapital(getCountry[0].capital);<br>  setCurrency(getCountry[0].currency);<br>  setPhone(getCountry[0].phone_code);<br>});</pre><p>At this point, our code will now look exactly like this, including the useEffect hook:</p><pre>&quot;use strict&quot;;<br>const React = require(&quot;react&quot;);<br>const { Text, Box } = require(&quot;ink&quot;);<br>const TextInput = require(&quot;ink-text-input&quot;).default;<br>const wcc = require(&quot;world-countries-capitals&quot;);<br><br>const App = () =&gt; {<br>  const [country, setCountry] = React.useState(&quot;&quot;);<br>  const [capital, setCapital] = React.useState(&quot;&quot;);<br>  const [currency, setCurrency] = React.useState(&quot;&quot;);<br>  const [phone, setPhone] = React.useState(&quot;&quot;);<br><br>  React.useEffect(() =&gt; {<br>    const getCountry = wcc.getCountryDetailsByName(country);<br>    setCapital(getCountry[0].capital);<br>    setCurrency(getCountry[0].currency);<br>    setPhone(getCountry[0].phone_code);<br>  });<br><br>  return (<br>    &lt;Box&gt;<br>      &lt;TextInput<br>        placeholder=&quot;Enter country...&quot;<br>        value={country}<br>        onChange={setCountry}<br>      /&gt;<br>    &lt;/Box&gt;<br>  );<br>};<br><br>module.exports = App;</pre><p>Let us now render our information in a table. We have to nest several boxes with specific attributes. The most common attributes we will be using are flex-direction and borderStyle. Since we are using React, we will need a parent attribute. We&#39;ll place our table beneath the TextBox element in the Box element.</p><pre>&lt;Box flexDirection=&quot;column&quot; width={80} borderStyle=&quot;single&quot;&gt;<br>  &lt;Box&gt;<br>    &lt;Box width=&quot;40%&quot;&gt;<br>      &lt;Text&gt;Country Code&lt;/Text&gt;<br>    &lt;/Box&gt;<br>    &lt;Box width=&quot;40%&quot;&gt;<br>      &lt;Text&gt;Capital City&lt;/Text&gt;<br>    &lt;/Box&gt;<br>    &lt;Box width=&quot;40%&quot;&gt;<br>      &lt;Text&gt;Currency&lt;/Text&gt;<br>    &lt;/Box&gt;<br>  &lt;/Box&gt;<br>  &lt;Box&gt;<br>    &lt;Box width=&quot;40%&quot;&gt;<br>      &lt;Text&gt;{phone}&lt;/Text&gt;<br>    &lt;/Box&gt;<br>    &lt;Box width=&quot;40%&quot;&gt;<br>      &lt;Text&gt;{capital}&lt;/Text&gt;<br>    &lt;/Box&gt;<br>    &lt;Box width=&quot;40%&quot;&gt;<br>      &lt;Text&gt;{currency}&lt;/Text&gt;<br>    &lt;/Box&gt;<br>  &lt;/Box&gt;<br>&lt;/Box&gt;;</pre><p>We will now add a banner to our application. We will add the banner within our root Box element on top of the text input.</p><pre>&lt;Box borderStyle=&quot;round&quot; borderColor=&quot;green&quot;&gt;<br>  &lt;Text&gt;Welcome to Country CLI App&lt;/Text&gt;<br>&lt;/Box&gt;;</pre><p>We are now done building our command-line app. The full code should look like this:</p><pre>&quot;use strict&quot;;<br>const React = require(&quot;react&quot;);<br>const { Text, Box } = require(&quot;ink&quot;);<br>const TextInput = require(&quot;ink-text-input&quot;).default;<br>const wcc = require(&quot;world-countries-capitals&quot;);<br><br>const App = () =&gt; {<br>  const [country, setCountry] = React.useState(&quot;&quot;);<br>  const [capital, setCapital] = React.useState(&quot;&quot;);<br>  const [currency, setCurrency] = React.useState(&quot;&quot;);<br>  const [phone, setPhone] = React.useState(&quot;&quot;);<br><br>  React.useEffect(() =&gt; {<br>    const getCountry = wcc.getCountryDetailsByName(country);<br>    setCapital(getCountry[0].capital);<br>    setCurrency(getCountry[0].currency);<br>    setPhone(getCountry[0].phone_code);<br>  });<br><br>  return (<br>    &lt;Box flexDirection=&quot;column&quot;&gt;<br>      &lt;Box borderStyle=&quot;round&quot; borderColor=&quot;green&quot;&gt;<br>        &lt;Text&gt;Welcome to Country CLI App&lt;/Text&gt;<br>      &lt;/Box&gt;<br>      &lt;TextInput<br>        placeholder=&quot;Enter Country&quot;<br>        value={country}<br>        onChange={setCountry}<br>      /&gt;<br>      &lt;Box flexDirection=&quot;column&quot; width={80} borderStyle=&quot;single&quot;&gt;<br>        &lt;Box&gt;<br>          &lt;Box width=&quot;40%&quot;&gt;<br>            &lt;Text&gt;Country Code&lt;/Text&gt;<br>          &lt;/Box&gt;<br>          &lt;Box width=&quot;40%&quot;&gt;<br>            &lt;Text&gt;Capital&lt;/Text&gt;<br>          &lt;/Box&gt;<br>          &lt;Box width=&quot;40%&quot;&gt;<br>            &lt;Text&gt;Currency&lt;/Text&gt;<br>          &lt;/Box&gt;<br>        &lt;/Box&gt;<br>        &lt;Box&gt;<br>          &lt;Box width=&quot;40%&quot;&gt;<br>            &lt;Text&gt;{phone}&lt;/Text&gt;<br>          &lt;/Box&gt;<br>          &lt;Box width=&quot;40%&quot;&gt;<br>            &lt;Text&gt;{capital}&lt;/Text&gt;<br>          &lt;/Box&gt;<br>          &lt;Box width=&quot;40%&quot;&gt;<br>            &lt;Text&gt;{currency}&lt;/Text&gt;<br>          &lt;/Box&gt;<br>        &lt;/Box&gt;<br>      &lt;/Box&gt;<br>    &lt;/Box&gt;<br>  );<br>};<br><br>module.exports = App;</pre><p>To run this code on your terminal, type node cli.js on your terminal, and you should get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*5Axc-n0_szNOGqO8.gif" /></figure><p>When you input your country, you get your capital and currency.</p><h3>Conclusion</h3><p>You can structure the terminal output in components using Ink in the same manner that you would, building a React app for the browser. You can quickly construct modern and interactive command-line interfaces with the Ink layout components. Ink supports Hooks, making it straightforward to access user input and add interactivity to your CLI.</p><p><em>Originally published at </em><a href="https://blog.openreplay.com/building-command-line-apps-using-react-ink"><em>blog.openreplay.com</em></a><em> on May 6, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df090dc6c60b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stackanatomy/building-command-line-apps-using-react-ink-df090dc6c60b">Building Command-Line Apps Using React Ink</a> was originally published in <a href="https://medium.com/stackanatomy">StackAnatomy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>