<?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>DEV Community: sherylmichaela</title>
    <description>The latest articles on DEV Community by sherylmichaela (@sherylmichaela).</description>
    <link>https://dev.to/sherylmichaela</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%2F1223567%2Fba5ecf6c-bc9c-47bf-be34-d8287214853d.jpeg</url>
      <title>DEV Community: sherylmichaela</title>
      <link>https://dev.to/sherylmichaela</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sherylmichaela"/>
    <language>en</language>
    <item>
      <title>Improving User Signup Experience: Auto-Login After Registration</title>
      <dc:creator>sherylmichaela</dc:creator>
      <pubDate>Tue, 10 Sep 2024 12:25:42 +0000</pubDate>
      <link>https://dev.to/sherylmichaela/improving-user-signup-experience-auto-login-after-registration-28kn</link>
      <guid>https://dev.to/sherylmichaela/improving-user-signup-experience-auto-login-after-registration-28kn</guid>
      <description>&lt;p&gt;When users sign up for a service, the best experience is one where they can jump straight into using the app without needing to go through multiple steps. I wanted users to be logged in immediately after creating their account, reducing friction. In this blog, I'll talk about how I implement this feature, using Flask for the backend and React on the frontend.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Frontend: React Signup Form&lt;/strong&gt;&lt;br&gt;
The signup process starts with a form where users enter their details (username, email, and password). To ensure a smooth and intuitive experience, I included validation checks and error handling on the frontend before any data is sent to the backend.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [signupError, setSignupError] = useState("");

async function signup(e) {
  e.preventDefault();

  try {
    const response = await fetch("/signup", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ username, email, password }),
    });

    const data = await response.json();

    if (response.ok) {
      setUser(data); 
    } else {
      setSignupError("Username/email already in use.");
    }
  } catch (error) {
    setSignupError("An error occurred. Please try again.");
  }
}

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Upon a successful POST request to /signup, the &lt;code&gt;setUser&lt;/code&gt; function is called, storing the user details, which also logs the user in by setting the global user state.&lt;/li&gt;
&lt;li&gt;If the response is unsuccessful, an error message is displayed, ensuring users are informed if something goes wrong.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Backend: Flask Signup and Auto-Login&lt;/strong&gt;&lt;br&gt;
On the server side, Flask handles the logic to create a new user and automatically logs them in by setting a session.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Signup(Resource):

    def post(self):
        try:
            user = User(username=request.json.get('username'), email=request.json.get('email'), hashed_password=request.json.get('password'))

            db.session.add(user)
            db.session.commit()

            session['user_id'] = user.id

            if user.id:
                session['user'] = user.to_dict() # Include to_dict() to make it JSON serialisable.

                return make_response(user.to_dict(), 201)

            return make_response({"error": "Signup unsucessful"}, 403)

        except ValueError as ve:
            return make_response({"error": str(ve)}, 409)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;After successfully creating a new user and committing it to the database, I store the user’s ID in the session, effectively logging them in.&lt;/li&gt;
&lt;li&gt;I also return the user’s data to the frontend, which updates the global state, allowing the user to navigate the app without needing to log in again.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
By combining frontend validation and an efficient backend session management process, users can now create their accounts and immediately start using the app without the hassle of logging in twice. This small yet impactful feature enhances the overall user experience, making the signup flow more seamless.&lt;/p&gt;

</description>
      <category>flask</category>
      <category>react</category>
    </item>
    <item>
      <title>A Step-by-Step Guide to Setting Up Class Resources for a Task Management App in Flask</title>
      <dc:creator>sherylmichaela</dc:creator>
      <pubDate>Sun, 04 Aug 2024 13:18:13 +0000</pubDate>
      <link>https://dev.to/sherylmichaela/a-step-by-step-guide-to-setting-up-class-resources-for-a-task-management-app-in-flask-2bpe</link>
      <guid>https://dev.to/sherylmichaela/a-step-by-step-guide-to-setting-up-class-resources-for-a-task-management-app-in-flask-2bpe</guid>
      <description>&lt;p&gt;For my current phase project, I've chosen to develop a Personal Task Management App. I'll use it to explain, step by step, how to set up class resources, &lt;code&gt;Tasks&lt;/code&gt; and &lt;code&gt;TaskById&lt;/code&gt;, using Flask. These classes will handle creating, retrieving, updating, and deleting tasks.&lt;/p&gt;

&lt;p&gt;Before you begin, make sure Python is installed in your system. Then, head to the terminal in VSCode and run the code below in the root folder:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pipenv install flask flask-sqlalchemy flask-restful
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 1: Set Up Your Flask Application&lt;/strong&gt;&lt;br&gt;
We'll create a new Flask app and configure the necessary components:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import Flask, request, session, make_response
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flask_migrate import Migrate
from flask_restful import Api, Resource
from datetime import datetime

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False
app.config['SECRET_KEY'] = 'your_secret_key'

db = SQLAlchemy()
migrate = Migrate(app, db)
db.init_app(app)
api = Api(app)
CORS(app)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This step involves setting up the basic configuration for your Flask application, including integrating SQLAlchemy for database management and Flask-RESTful for building RESTful APIs.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Flask&lt;/code&gt;: The main framework to create web apps&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;request&lt;/code&gt;: To handle incoming HTTP requests&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;session&lt;/code&gt;: To manage user sessions (e.g., storing user_id when a user is logged in).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;make_response&lt;/code&gt;: To create HTTP responses.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;SQLAlchemy&lt;/code&gt;: A SQL toolkit and Object-Relational Mapping (ORM) system.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;CORS&lt;/code&gt;: Cross-Origin Resource Sharing (CORS), restricts web pages from making requests to a different domain than the one that served the web page.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Migrate&lt;/code&gt;: To handle database migrations in a Flask application&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Api, Resource&lt;/code&gt;: Provided by Flask-RESTful, used to create RESTful API endpoints.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;datetime&lt;/code&gt;: To handle date and time-related tasks&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Define &lt;code&gt;Task&lt;/code&gt; Model&lt;/strong&gt;&lt;br&gt;
Next, define the Task model, which represents a task in your database:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Task(db.Model):
    __tablename__ = "tasks"

    id = db.Column(db.Integer, primary_key=True)
    task_name = db.Column(db.String(255), nullable=False)
    category = db.Column(db.String(255))
    task_due_date = db.Column(db.DateTime)
    task_status = db.Column(db.String, default="pending")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Create the &lt;code&gt;Tasks&lt;/code&gt; and &lt;code&gt;TaskById&lt;/code&gt; Resource&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;Tasks&lt;/code&gt; resource will handle requests to the &lt;code&gt;/tasks&lt;/code&gt; endpoint. It will allow users to retrieve and create tasks.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;TaskById&lt;/code&gt; resource will handle requests to the &lt;code&gt;/tasks/&amp;lt;int:id&amp;gt;&lt;/code&gt; endpoint. It will allow users to retrieve, update, and delete a specific task.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Tasks(Resource):
    # /tasks

    def get(self):

        if 'user_id' in session:
            my_tasks = Task.query.filter(Task.user_id == session['user_id']).all()

            if len(my_tasks) &amp;gt; 0:
                tasks = [task.to_dict() for task in my_tasks]
                return make_response(tasks, 200)

            return make_response({"message": "No task created yet"}, 200)

        return make_response({"error": "Pls log in to view tasks."}, 401)

    def post(self):
        task_name = request.json.get('task_name')
        category = request.json.get('category')
        task_due_date = datetime.strptime(request.json.get('task_due_date'), '%Y-%m-%d')
        task_status = request.json.get('task_status', 'pending')

        new_task = Task(task_name=task_name, category=category, task_due_date=task_due_date, task_status=task_status, user_id=session['user_id'])

        db.session.add(new_task)
        db.session.commit()

        if new_task.id:
            return make_response(new_task.to_dict(), 201)

        return make_response({"error": "error occurred"}, 400)


class TaskById(Resource):
    # /tasks/&amp;lt;int:id&amp;gt;

    @classmethod
    def find_task(cls, id):
        return Task.query.filter(and_(Task.id == id, Task.user_id == session['user_id'])).first()

    def get(self, id):

        if 'user_id' in session:
            task = TaskById.find_task(id)

        if task:
            return make_response(task.to_dict(), 200)

        return make_response({"error": "This task doesn't exist or you may not have permission to view this task"}, 401)

    def patch(self, id):
        task = TaskById.find_task(id)

        if task:
            for attr in request.json:
                if attr == "task_due_date":
                    request.json[attr] = datetime.strptime(request.json[attr], '%Y-%m-%d')  
                setattr(task, attr, request.json[attr])

            db.session.commit()

            return make_response(task.to_dict(), 200)

        return make_response({"error": "No task found"}, 404)

    def delete(self, id):
        task = TaskById.find_task(id)

        if task:
            db.session.delete(task)
            db.session.commit()

            return make_response({"message": "Task is deleted successfully"}, 200)

        return make_response({"error": "No task found"}, 404)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4: Add Resources to the API&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;api.add_resource(Tasks, '/tasks')
api.add_resource(TaskById, '/tasks/&amp;lt;int:id&amp;gt;')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;db&lt;/code&gt;: An instance of SQLAlchemy, initialized with the Flask application instance. This sets up the connection between the Flask app and the database, allowing you to define and interact with database models.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;api&lt;/code&gt;: An instance of Flask-RESTful's Api. This sets up the framework for adding RESTful API resources to your application.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>flask</category>
    </item>
    <item>
      <title>Basic Operations and Integration in Python &amp; SQLite</title>
      <dc:creator>sherylmichaela</dc:creator>
      <pubDate>Thu, 06 Jun 2024 04:14:52 +0000</pubDate>
      <link>https://dev.to/sherylmichaela/basic-operations-and-integration-in-python-sqlite-4900</link>
      <guid>https://dev.to/sherylmichaela/basic-operations-and-integration-in-python-sqlite-4900</guid>
      <description>&lt;p&gt;In this blog post, I aim to cover some fundamental operations and integration techniques for using Python with SQL. Given my tendency to be a bit forgetful, this blog will serve as a handy reminder for setting up a Python SQLite environment from scratch, and I hope it will benefit you too!&lt;/p&gt;

&lt;p&gt;I will be using a recent restaurant food order app which I did for my phase project as an example in this post. You can fork this project using this &lt;a href="https://github.com/sherylmichaela/phase-3-restaurant-food-order-app.git"&gt;link&lt;/a&gt; to follow along.&lt;/p&gt;




&lt;h2&gt;
  
  
  How to connect Python to SQLite Database?
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Create the root directory. i.e. &lt;code&gt;restaurant-food-order-app&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Create a sub-directory and name it &lt;code&gt;lib&lt;/code&gt;. All your &lt;code&gt;.py&lt;/code&gt; files will live here.&lt;/li&gt;
&lt;li&gt;Inside the &lt;code&gt;lib&lt;/code&gt; folder, create a &lt;code&gt;models.py&lt;/code&gt; file.&lt;/li&gt;
&lt;li&gt;Inside Terminal, navigate to the &lt;code&gt;/restaurant-food-order-app/&lt;/code&gt; directory. Install dependencies such as SQLAlchemy and Alembic using &lt;code&gt;pipenv install sqlalchemy alembic&lt;/code&gt;. The &lt;code&gt;pipenv&lt;/code&gt; tool is used for managing Python dependencies, virtual environments, and &lt;code&gt;Pipfile&lt;/code&gt; dependencies.&lt;/li&gt;
&lt;li&gt;Run &lt;code&gt;pipenv shell&lt;/code&gt; to run the virtual environment.&lt;/li&gt;
&lt;li&gt;Import required modules, initialise the database and define the models. You can refer to my &lt;code&gt;models.py&lt;/code&gt; file.&lt;/li&gt;
&lt;li&gt;Initialise Alembic by running &lt;code&gt;alembic init migrations&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Locate and open the &lt;code&gt;alembic.ini&lt;/code&gt; file. Look for &lt;code&gt;sqlalchemy.url&lt;/code&gt; setting. Modify the URL which points to your database. i.e. &lt;code&gt;sqlalchemy.url = sqlite:///lib/data.db&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Locate and open the &lt;code&gt;env.py&lt;/code&gt; file. Look for &lt;code&gt;target_metadata = None&lt;/code&gt; and replace it with:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from models import Base
target_metadata = Base.metadata
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;from models import Base&lt;/code&gt; imports the base class for your SQLAlchemy models.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;target_metadata = Base.metadata&lt;/code&gt; sets Alembic’s target metadata to the collection of table definitions from your SQLAlchemy models, enabling Alembic to manage and synchronise your database schema based on these definitions.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Once all of the above is done, run &lt;code&gt;alembic revision --autogenerate -m "Create models"&lt;/code&gt;. This is used to create a new Alembic revision file that includes automatically generated migration scripts. Then, run &lt;code&gt;alembic upgrade head&lt;/code&gt; to upgrade to the latest database version. Run &lt;code&gt;alembic current&lt;/code&gt; to check the current database version you're in.&lt;/p&gt;




&lt;h2&gt;
  
  
  How to set up a SQLAlchemy engine and session for interacting with a SQLite database?
&lt;/h2&gt;

&lt;p&gt;Create a &lt;code&gt;config.py&lt;/code&gt; file inside the &lt;code&gt;lib&lt;/code&gt; folder. Include the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine("sqlite:///lib/data.db")
Session = sessionmaker(bind=engine)
session = Session()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;create_engine&lt;/code&gt; is a function from SQLAlchemy that creates a new database engine instance.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sessionmaker&lt;/code&gt; is a factory for creating new Session objects, which are used to interact with the database.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;create_engine("sqlite:///lib/data.db")&lt;/code&gt; creates a new SQLAlchemy engine that connects to a SQLite database located at lib/data.db.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sessionmaker(bind=engine)&lt;/code&gt; creates a configurable session factory, Session, which will create Session objects that are bound to the engine. Binding the session to the engine means that any session created by this factory will use the specified engine to connect to the database.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Session()&lt;/code&gt; creates an instance of a session object from the session factory. This session object is used to interact with the database. You can use it to execute queries, add and delete objects, and commit transactions.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Once done, you can import the above in your other &lt;code&gt;.py&lt;/code&gt; files to interact with your database by including the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from config import session
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  SQL Queries and CRUD Operations in Python
&lt;/h2&gt;

&lt;p&gt;With everything set in place, you can now proceed to perform various database operations. In this example, I will be working with the &lt;code&gt;Customer&lt;/code&gt; object which has the following attributes: &lt;code&gt;first_name&lt;/code&gt;, &lt;code&gt;last_name&lt;/code&gt; and &lt;code&gt;mobile&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Adding an Object:&lt;/strong&gt; 
This code adds a new Customer object to the database and commits the transaction.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;new_customer = Customer(first_name="John", last_name="Doe", mobile="0412345678")
session.add(new_customer)
session.commit()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Querying the Database:&lt;/strong&gt; 
This code retrieves all Customer objects from the database and prints their first and last names.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;customers = session.query(Customer).all()
for customer in customers:
   print(f"{customer.first_name} {customer.last_name}")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Updating an Object:&lt;/strong&gt; 
This code updates the first name of the first user found with the mobile "0412345678" to "Andy" and commits the transaction.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;customer = session.query(Customer).filter(mobile="0412345678").first()
customer.first_name = "Andy"
session.commit()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Deleting an Object:&lt;/strong&gt; 
This code deletes the user named "Andy Doe" from the database and commits the transaction.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;customer = session.query(Customer).filter(first_name="Andy", last_name="Doe").first()
session.delete(customer)
session.commit()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>python</category>
      <category>sql</category>
    </item>
    <item>
      <title>What are useState, useEffect and useRef hooks?</title>
      <dc:creator>sherylmichaela</dc:creator>
      <pubDate>Fri, 29 Mar 2024 23:47:42 +0000</pubDate>
      <link>https://dev.to/sherylmichaela/what-are-usestate-useeffect-and-useref-hooks-4a6c</link>
      <guid>https://dev.to/sherylmichaela/what-are-usestate-useeffect-and-useref-hooks-4a6c</guid>
      <description>&lt;p&gt;In this post, I'd like to touch on some of the commonly used React hooks. React hooks are first introduced in React 16.8. They allow functional components to use state, side effects, and create references to DOM elements respectively. They let you use state and other React features without writing a class.&lt;/p&gt;

&lt;h2&gt;
  
  
  useState
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;const [count, setCount] = useState(0)&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;useState&lt;/code&gt; is a hook that allows functional components to manage state within the component.&lt;/li&gt;
&lt;li&gt;When you call useState, it returns an array with two elements: the current state value and a function that lets you update it. (i.e. &lt;code&gt;[count, setCount]&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;The initial state is passed as an argument to useState. (i.e. &lt;code&gt;useState(0)&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Applying the &lt;code&gt;useState&lt;/code&gt; hook&lt;/strong&gt;&lt;br&gt;
I like to use the useState hook to manipulate button states.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [buttonText, setButtonText] = useState("Add To Cart");
const [buttonDisabled, setButtonDisabled] = useState(false);

const handleClick = () =&amp;gt; {
    setButtonText("Added to Cart!");
    setButtonDisabled(true);
  };

&amp;lt;Button variant="primary"
        disabled={buttonDisabled}
        onClick={handleClick}&amp;gt;
        {buttonText}
&amp;lt;/Button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What this code does:&lt;br&gt;
It creates a button component that starts enabled with the text "Add To Cart". When clicked, the text changes to "Added to Cart!" and the button becomes disabled.&lt;/p&gt;

&lt;p&gt;Explanation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The initial value of buttonText is set to "Add To Cart", and the initial value of buttonDisabled is set to a Boolean value.&lt;/li&gt;
&lt;li&gt;The useState hook returns an array with two elements: the current state value and a function to update that value.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;handleClick&lt;/code&gt; function will be called when the button is clicked. Inside this function, setButtonText is called with the argument "Added to Cart!" to update the button text, and setButtonDisabled is called with true to disable the button.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  useEffect
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
    document.title = `You clicked ${count} times`;
  }, [count]); // Only re-run the effect if count changes
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;useEffect&lt;/code&gt; is a hook that allows functional components to perform side effects (such as data fetching, subscriptions, or manually changing the DOM) after the component renders.&lt;/li&gt;
&lt;li&gt;It takes a function as its first argument, which contains the code for the side effect.&lt;/li&gt;
&lt;li&gt;By default, useEffect runs after every render, including the initial render.&lt;/li&gt;
&lt;li&gt;You can specify dependencies as the second argument to control when the effect is re-run.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Applying the &lt;code&gt;useEffect&lt;/code&gt; hook&lt;/strong&gt;&lt;br&gt;
This hook is commonly utilised for fetching data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [wishlistItems, setWishlistItems] = useState([]);

useEffect(() =&amp;gt; {
    fetch("http://localhost:4000/wishlist")
      .then((response) =&amp;gt; response.json())
      .then((json) =&amp;gt; {
        setWishlistItems(json);
      });
  }, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What this code does:&lt;br&gt;
It fetches wishlist items from a server when the component mounts and updates the component's state with the fetched data.&lt;/p&gt;

&lt;p&gt;Explanation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;useEffect&lt;/code&gt; is like a special function in React that runs some code when something in the component changes.&lt;/li&gt;
&lt;li&gt;In this example, it initiates a fetch request to the specified URL and fetches data from the server.&lt;/li&gt;
&lt;li&gt;Next, it chains a 'then' method to the fetch call to parse the response body as JSON. This converts the response from the server into a JavaScript object.&lt;/li&gt;
&lt;li&gt;It then chains another 'then' method to handle the parsed JSON data. Here, it updates the 'wishlistItems' state with the fetched JSON data.&lt;/li&gt;
&lt;li&gt;Finally, the hook is configured with an empty dependency array [], which ensures that the effect runs only once after the component mounts.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  useRef
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;const target = useRef(null);&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;useRef&lt;/code&gt; Hook allows you to reference a value that’s not needed for rendering.&lt;/li&gt;
&lt;li&gt;It can be used to store a mutable value that does not cause a re-render when updated.&lt;/li&gt;
&lt;li&gt;It can be used to access a DOM element directly.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Applying the &lt;code&gt;useRef&lt;/code&gt; hook&lt;/strong&gt;&lt;br&gt;
In my project, I used the &lt;code&gt;useRef&lt;/code&gt; hook to create a reference to a DOM element (the button) so that it can be accessed and used elsewhere in the component, such as positioning an overlay relative to the button.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [show, setShow] = useState(false);
const target = useRef(null);

const handleAddToWishlistBtn = () =&amp;gt; {
    setShow(true);

    setTimeout(() =&amp;gt; {
      setShow(false);
    }, 2000);

  };

&amp;lt;Button
          variant="danger"
          ref={target}
          onClick={handleAddToWishlistBtn}
        &amp;gt;
          Add to Wishlist
&amp;lt;/Button&amp;gt;
        &amp;lt;Overlay target={target.current} show={show} placement="right"&amp;gt;
          {(props) =&amp;gt; (
            &amp;lt;Tooltip id="overlay-example" {...props}&amp;gt;
              Added to Wishlist!
            &amp;lt;/Tooltip&amp;gt;
          )}
        &amp;lt;/Overlay&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What this code does:&lt;br&gt;
When the "Add to Wishlist" button is clicked, an overlay tooltip appears next to it, displaying the message "Added to Wishlist!". The tooltip disappears after 2 seconds. The positioning of the tooltip is determined by the button element.&lt;/p&gt;

&lt;p&gt;Explanation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;const target = useRef(null)&lt;/code&gt; here is used to reference my button element without causing unnecessary re-renders when the ref's value is updated.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;target.current&lt;/code&gt; reference is then passed as the target prop to the  component. This allows the overlay to position itself relative to the button element.&lt;/li&gt;
&lt;li&gt;As such, when the  component is triggered to appear or disappear, it doesn't cause the entire page to re-render. Instead, React only updates the parts of the DOM that have changed, which in this case would be the rendering of the overlay itself.&lt;/li&gt;
&lt;/ol&gt;

</description>
    </item>
    <item>
      <title>Phase 1 - Javascript</title>
      <dc:creator>sherylmichaela</dc:creator>
      <pubDate>Sat, 10 Feb 2024 01:00:04 +0000</pubDate>
      <link>https://dev.to/sherylmichaela/phase-1-javascript-3k62</link>
      <guid>https://dev.to/sherylmichaela/phase-1-javascript-3k62</guid>
      <description>&lt;p&gt;Navigating through Phase 1, delving into the intricacies of JavaScript has been quite a challenge. While working on the Phase 1 project, I've found the experience enjoyable, yet it has underscored the vast scope for further improvement. In this blog, I intend to outline the processes and hurdles encountered during the project and share the valuable lessons gleaned from these experiences.&lt;/p&gt;

&lt;p&gt;The primary objective of this project revolves around the utilisation of the Fetch API, facilitating API requests for data retrieval and server data submission. Given the abundance of concepts not covered in this phase, a significant portion of the project involves extensive research and trial-and-error to ensure the seamless functionality of this Single Page Application (SPA).&lt;/p&gt;

&lt;p&gt;The first lesson learned was the effective use of the &lt;code&gt;"change"&lt;/code&gt; event and &lt;code&gt;event.target.value&lt;/code&gt; to access an element's value. This knowledge proved crucial in utilising the chosen value within the fetch(url) through string interpolation, enabling access to the relevant API endpoint.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; dropDown.addEventListener("change", (event) =&amp;gt; {
    currentValue = event.target.value;
  });

let url = `http://www.boredapi.com/api/activity?participants=${currentValue}`
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Additionally, I discovered that I could employ the &lt;code&gt;.type&lt;/code&gt; and &lt;code&gt;.className&lt;/code&gt; properties in JavaScript to define the type and class attributes for the 'Save' and 'Delete' buttons. This allowed me to utilise Bootstrap button styles effectively, especially considering that these buttons are generated only when the function is invoked.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Save button
   saveBtn = document.createElement("button");
   saveBtn.type = "button";
   saveBtn.className = "btn btn-primary save-btn";
   saveBtn.innerHTML = "Save";

// Delete button
   deleteBtn = document.createElement("button");
   deleteBtn.type = "button";
   deleteBtn.className = "btn btn-danger delete-btn";
   deleteBtn.innerHTML = "Delete";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Furthermore, the act of populating the retrieved data and arranging it within table rows provided an opportunity to apply diverse document methods such as &lt;code&gt;.querySelector()&lt;/code&gt;, &lt;code&gt;.createElement()&lt;/code&gt;, &lt;code&gt;.innerHTML&lt;/code&gt;, and &lt;code&gt;.appendChild()&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let table = document.querySelector("#tbody");
let row = document.createElement("tr");
table.appendChild(row);

// Create columns
   let c1 = document.createElement("td");
   let c2 = document.createElement("td");
   let c3 = document.createElement("td");
   let c4 = document.createElement("td");
   let c5 = document.createElement("td");

// Activity data input into table
   c1.innerHTML = data.activity;
   c2.innerHTML = data.type.charAt(0).toUpperCase() + data.type.slice(1);
   c3.innerHTML = data.accessibility;
   c4.appendChild(saveBtn);
   c5.appendChild(deleteBtn);

// Adding td element with activity info to tr element
   row.appendChild(c1);
   row.appendChild(c2);
   row.appendChild(c3);
   row.appendChild(c4);
   row.appendChild(c5);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, a notable aspect of this phase involved mastering the utilisation of the JavaScript Object Notation (JSON) server to generate mock APIs without the necessity for intricate server-side coding. Throughout this project, I successfully employed the post method to transmit data, such as the activity name, type, and accessibility rating, to the mock server. This newfound skill will undoubtedly prove invaluable in my future front-end development endeavours, particularly when a backend API is not yet available.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Posting data to json server using the save button
   saveBtn.addEventListener("click", () =&amp;gt; {
     return fetch("http://localhost:3000/data", {
       method: "POST",
       headers: {
         "Content-Type": "application/json",
         Accept: "application/json",
       },
       body: JSON.stringify({
         activity: data.activity,
         type: data.type,
         accessibility: data.accessibility,
       }),
     }).then((response) =&amp;gt; response.json());
   });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While the JavaScript phase was brief, there remains a wealth of knowledge to explore. It was challenging to absorb all the information within this limited timeframe. Fortunately, technology, particularly platforms like Google, allows us to leverage the online collective expertise to troubleshoot and improve the functionality of my code.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Here goes nothing...</title>
      <dc:creator>sherylmichaela</dc:creator>
      <pubDate>Fri, 01 Dec 2023 11:11:11 +0000</pubDate>
      <link>https://dev.to/sherylmichaela/here-goes-nothing-2on</link>
      <guid>https://dev.to/sherylmichaela/here-goes-nothing-2on</guid>
      <description>&lt;p&gt;Starting a new habit of writing blogs to kickstart my software engineering journey. 😁&lt;/p&gt;

</description>
      <category>beginners</category>
    </item>
  </channel>
</rss>
