Thursday, 19 December 2024

How to Send Data with the Fetch API in React: A Guide to POST Requests?

In this tutorial, we will demonstrate how to create a React component that allows users to submit new posts via a form and then display a list of the posts they've published, dynamically updating the list whenever a new post is submitted.


We'll be using the free API provided by JSONPlaceholder, specifically the endpoint https://jsonplaceholder.typicode.com/posts to simulate publishing posts.

 

Follow below step-by-step procedure to build the complete working application.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘post-request-demo’.

 

Project structure looks like below.


 

Step 2: Create components folder in src folder and define PublishAndDisplayPost component.

 

PublishAndDisplayPost.jsx

import { useState } from "react";

export default function PublishAndDisplayPost() {
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");
  const [posts, setPosts] = useState([]);

  async function createNewPost() {
    try {
      const response = await fetch(
        "https://jsonplaceholder.typicode.com/posts",
        {
          method: "POST",
          body: JSON.stringify({
            title: title, // Corrected
            body: body, // Corrected
            userId: 1,
          }),
          headers: {
            "Content-type": "application/json; charset=UTF-8",
          },
        }
      );

      const responseData = await response.json();
      console.log(`responseData : ${JSON.stringify(responseData)}`);

      setTitle("");
      setBody("");

      const newPost = {
        title: responseData.title,
        body: responseData.body,
      };

      console.log(`newPost is ${JSON.stringify(newPost)}`);

      setPosts([...posts, newPost]); // Corrected
    } catch (error) {
      console.error("Error:", error);
    }
  }

  return (
    <>
      <form
        onSubmit={(event) => {
          event.preventDefault();
          createNewPost();
        }}
      >
        <p>
          <label htmlFor="title">Provide a title for your post</label> &nbsp;
          <input
            type="text"
            id="title"
            name="title"
            value={title}
            onChange={(event) => {
              setTitle(event.target.value);
            }}
          />
        </p>
        <p>
          <label htmlFor="body">Provide Body for your post</label> &nbsp; &nbsp;
          <textarea
            type="text"
            id="body"
            name="body"
            value={body}
            rows="10"
            cols="50"
            onChange={(event) => {
              setBody(event.target.value);
            }}
          />
        </p>
        <p>
          <button>Submit</button>
        </p>
        <ul>
          {posts.length > 0 ? <h1>Your posts</h1> : ""}
          {posts.map((post, index) => (
            <li key={index}>
              <strong>{post.title}:</strong> {post.body}
            </li>
          ))}
        </ul>
      </form>
    </>
  );
}

 

Step 3: Update main.jsx file with below content.

 

main.jsx

 

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import PublishAndDisplayPost from './components/PublishAndDisplayPost'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <PublishAndDisplayPost />
  </StrictMode>,
)

 

Step 4: Build and run the Application by executing below commands.

  cd post-request-demo
  npm install
  npm run dev

Open the url ‘http://localhost:5173/’ in browser, you will see below screen.


Enter some data to the text boxes and click on Submit button, you will see the same information below Submit button.



Previous                                                    Next                                                    Home

Building a Simple Queue in JavaScript Using Array Functions

A queue is a linear data structure that follows the First In, First Out (FIFO) principle. This means that the first element added to the queue will be the first one to be removed. Queues are commonly used in scenarios where order matters, such as in task scheduling, handling requests in web servers, or managing processes in operating systems.

Key Operations of a Queue

1.   Enqueue: Add an element to the end of the queue.

2.   Dequeue: Remove and return the element from the front of the queue.

3.   Peek: Look at the element at the front of the queue without removing it.

4.   IsEmpty: Check if the queue is empty.

5.   Size: Get the number of elements in the queue.

 

Advantages of Using a Queue

1.   Order Maintenance: Ensures that the elements are processed in the exact order they were added.

2.   Simplicity: The FIFO behaviour of a queue makes it easy to manage tasks that need to be processed in a specific order.

3.   Efficiency: Queues are efficient in managing tasks like scheduling and buffering.

 

Implementing a Queue in JavaScript Using shift() and push()

In JavaScript, arrays can be used to implement a queue. The push() method is used to add an element to the end of the array, and the shift() method is used to remove an element from the front of the array. This mimics the behaviour of a queue.

 

queue.js

// Enqueue function: Adds an element to the end of the queue
function enqueue(queue, element) {
    queue.push(element);
}

// Dequeue function: Removes and returns the element at the front of the queue
function dequeue(queue) {
    if (isEmpty(queue)) {
        return "Queue is empty";
    }
    return queue.shift();
}

// Peek function: Returns the element at the front of the queue without removing it
function peek(queue) {
    if (isEmpty(queue)) {
        return "Queue is empty";
    }
    return queue[0];
}

// IsEmpty function: Checks if the queue is empty
function isEmpty(queue) {
    return queue.length === 0;
}

// Size function: Returns the number of elements in the queue
function size(queue) {
    return queue.length;
}

// PrintQueue function: Returns a string representation of the queue
function printQueue(queue) {
    return 'Elements in Queue are: ' + queue.toString();
}

// Example usage
let myQueue = [];

console.log(`Is Queue empty?: ${isEmpty(myQueue)}`);

console.log('Add 10, 20 and 30 to the Queue')
enqueue(myQueue, 10);
enqueue(myQueue, 20);
enqueue(myQueue, 30);

console.log(printQueue(myQueue));

console.log(`Removing one element from the Queue ${dequeue(myQueue)}`);
console.log(`Top element of the Queue: ${peek(myQueue)}`);

console.log(`Size of the Queue: ${size(myQueue)}`);
console.log(`Is Queue empty?: ${isEmpty(myQueue)}`);

console.log(printQueue(myQueue));

Output

Is Queue empty?: true
Add 10, 20 and 30 to the Queue
Elements in Queue are: 10,20,30
Removing one element from the Queue 10
Top element of the Queue: 20
Size of the Queue: 2
Is Queue empty?: false
Elements in Queue are: 20,30

Explanation of the Functions

enqueue(queue, element): Adds an element to the end of the queue. ‘enqueue’ function uses the push() method to add the element to the end of the queue array.

 

dequeue(queue): Removes and returns the element at the front of the queue. ‘dequeue’ function Uses the shift() method to remove and return the first element in the queue array. If the queue is empty, it returns a message "Queue is empty."

 

peek(queue): This function returns the element at the front of the queue without removing it. It just returns the first element in the queue array. If the queue is empty, it returns a message "Queue is empty."

 

isEmpty(queue): Checks whether the queue is empty or not. It returns true if the queue array has no elements, otherwise, it returns false.

 

size(queue): Returns the number of elements in the queue. It just returns the length of the queue array.

 

printQueue(queue): It prints the elements of queue.


  

Previous                                                    Next                                                    Home

Font Families In css

In CSS, a font family refers to a set of fonts that share common design features. When you specify a font family in your CSS, you're essentially telling the browser which fonts to use to display the text on a webpage. If the first font specified is not available or supported on the user's device, the browser will try the next font in the list, and so on.

 

Syntax

font-family: "font 1", "font 2", generic-family;

 

Example

font-family: Georgia, Times, "Times New Roman", serif;

 

Main Generic Font Families in CSS

1. Serif: Fonts that have small lines or strokes attached to the end of a larger stroke in a letter or symbol. They are often used in print media and are considered more traditional.

 

·      Examples: Times New Roman, Georgia, Garamond.

·      Use Case: Great for body text in print, formal documents, and any context where a classic, readable look is desired.

 

2. Sans-serif: Fonts without the small lines at the ends of characters. They are cleaner and more modern looking, often used in digital interfaces.

 

·      Examples: Arial, Helvetica, Verdana.

·      Use Case: Suitable for websites, mobile apps, and any context requiring a modern, clean appearance. Sans-serif fonts are typically easier to read on screens.

 

3. Monospace: All characters occupy the same amount of horizontal space. These fonts are often used in coding environments and technical documentation.

 

·      Examples: Courier New, Consolas, Monaco.

·      Use Case: Ideal for displaying code snippets, technical documents, and any context where alignment of characters is important.

 

4. Cursive: Fonts that mimic handwritten or calligraphic text. They are generally more decorative and can add a personal or artistic touch.

 

·      Examples: Brush Script, Pacifico, Comic Sans MS.

·      Use Case: Best used sparingly, for informal designs, personal messages, or artistic elements where a handwritten feel is desired.

 

5. Fantasy: Decorative fonts that are often used for special effects. These are not intended for large bodies of text.

 

·      Examples: Impact, Papyrus, Jokerman.

·      Use Case: Good for headings, logos, or any design element where a unique and eye-catching font is needed.

 

fontFamily.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Font Family Examples</title>
    <style>
        body {
            font-family: Arial, sans-serif; /* Default to sans-serif for body */
            margin: 20px;
        }

        .serif {
            font-family: "Times New Roman", Times, serif;
        }

        .sans-serif {
            font-family: "Helvetica Neue", Arial, sans-serif;
        }

        .monospace {
            font-family: "Courier New", Courier, monospace;
        }

        .cursive {
            font-family: "Brush Script MT", cursive;
        }

        .fantasy {
            font-family: Impact, fantasy;
        }

        h1 {
            font-size: 24px;
            margin-bottom: 10px;
        }

        p {
            font-size: 16px;
            line-height: 1.6;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>

    <h1>Font Family Examples</h1>

    <section class="serif">
        <h1>Serif Font Example</h1>
        <p>This paragraph is styled with a serif font family. Serif fonts have small lines or strokes at the ends of each character. They are often used in traditional and formal contexts, such as in books and newspapers. This text is using "Times New Roman", Times, serif.</p>
    </section>

    <section class="sans-serif">
        <h1>Sans-serif Font Example</h1>
        <p>This paragraph is styled with a sans-serif font family. Sans-serif fonts do not have the small lines or strokes at the ends of characters. They are clean, modern, and widely used for web content. This text is using "Helvetica Neue", Arial, sans-serif.</p>
    </section>

    <section class="monospace">
        <h1>Monospace Font Example</h1>
        <p>This paragraph is styled with a monospace font family. Monospace fonts have characters that occupy the same amount of horizontal space, making them ideal for code and technical documents. This text is using "Courier New", Courier, monospace.</p>
    </section>

    <section class="cursive">
        <h1>Cursive Font Example</h1>
        <p>This paragraph is styled with a cursive font family. Cursive fonts are designed to mimic handwriting and often include decorative elements. They are used for artistic and personal touches. This text is using "Brush Script MT", cursive.</p>
    </section>

    <section class="fantasy">
        <h1>Fantasy Font Example</h1>
        <p>This paragraph is styled with a fantasy font family. Fantasy fonts are decorative and unconventional, often used for special effects or themed designs. They stand out and are not typically used for body text. This text is using Impact, fantasy.</p>
    </section>

</body>
</html>

 

Above snippet generate below screen.


 

 


Previous                                                    Next                                                    Home

Create Tables using HTML table element

The <table> element in HTML is used to create a table that organizes data into rows and columns. A table consists of multiple elements, some are given below.

 

1.   <table>: The container for the table.

2.   <tr> (table row): Defines a row in the table.

3.   <th> (table header): Defines a header cell, which is usually bold and centered. It represents column headings.

4.   <td> (table data): Defines the regular data cells in the table.

5.   <caption>: Provides a title or description for the table.

 

Optionally, you can group rows into sections using <thead>, <tbody>, and <tfoot> for more complex tables.

 

basic-table.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML Table Example</title>
</head>
<body>
    <h1>HTML Table Example</h1>
    
    <table border="1">
        <caption>Student Grades</caption>
        <thead>
            <tr>
                <th>Student Name</th>
                <th>Subject</th>
                <th>Grade</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Rama Krishna</td>
                <td>Math</td>
                <td>A</td>
            </tr>
            <tr>
                <td>Sailaja</td>
                <td>Computer Science</td>
                <td>B+</td>
            </tr>
            <tr>
                <td>Nagarjuna</td>
                <td>History</td>
                <td>A+</td>
            </tr>
        </tbody>
    </table>
    
</body>
</html>

 


Explanation

1.   <table border="1">: Creates the table with borders. You can adjust the border size or remove it if not needed.

2.   <caption>: Provides a title for the table, "Student Grades."

3.   <thead>: Contains the table's header row (Student Name, Subject, Grade).

4.   <tbody>: Holds the main data, organized in rows with <tr>. Each row contains <td> elements for individual data cells (e.g., "Rama Krishna", "Math", "A").


 

Previous                                                    Next                                                    Home