Thursday, 5 December 2024

Using Async and Await with the useEffect Hook in React to Fetch Data

This is continuation to my previous post, where I explained how to render the user details using promises and useEffect hook.

useEffect(() => {
    // This effect will run when the component is first rendered

    // Fetching data from an API
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(data => setUsers(data))  // Update the state with the fetched data
      .catch(error => console.error('Error fetching users:', error));

}, []);  // The empty dependency array means this runs only on the first render (once)

Above snippet can be written like below.

useEffect(() => {
    // This effect will run when the component is first rendered

    async function fetchUsers() {
      try {
        let response = await fetch(
          "https://jsonplaceholder.typicode.com/users"
        );
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        let data = await response.json();
        setUsers(data);
      } catch (error) {
        console.error("Failed to fetch users:", error);
      }
    }

    fetchUsers();
  }, []); // The empty dependency array means this run only on the first render (once)

This code uses the useEffect hook to fetch a list of users from an external API (jsonplaceholder.typicode.com/users) when the component is first rendered. The fetchUsers function makes the request asynchronously, processes the response into JSON format, and updates the component's state with the retrieved data using setUsers. If the fetch operation fails, the error is caught and logged to the console. The effect runs only once because of the empty dependency array.

 

 

Follow below step-by-step procedure to build the 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 ‘async-await-with-use-effect’.

 

Project structure looks like below.

 


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

 

UsersInfo.jsx

import React, { useState, useEffect } from "react";

export default function UsersInfo() {
  const [users, setUsers] = useState([]); // State to hold the users

  useEffect(() => {
    // This effect will run when the component is first rendered

    async function fetchUsers() {
      try {
        let response = await fetch(
          "https://jsonplaceholder.typicode.com/users"
        );
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        let data = await response.json();
        setUsers(data);
      } catch (error) {
        console.error("Failed to fetch users:", error);
      }
    }

    fetchUsers();
  }, []); // The empty dependency array means this runs only on the first render (once)

  return (
    <div>
      <h1>User List</h1>
      <ul>
        {users.map((user) => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

Step 3: Update main.jsx like below.

 

main.jsx

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

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

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

  cd async-await-with-use-effect
  npm install
  npm run dev

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


 


You can download this application from this link.

 

Previous                                                    Next                                                    Home

Rest Parameters in JavaScript to accept an indefinite number of arguments

Rest parameters in JavaScript allow a function to accept an indefinite number of arguments as an array. This is useful when you want to create functions that can handle more arguments than you originally defined.

How Rest Parameters Work?

Rest parameters are indicated by three dots (...) followed by the name of the array that will hold the arguments. This syntax tells JavaScript to gather all remaining arguments into a single array.

 

Syntax

function functionName(...restParameter) {
  // function body
}

Example 1: Same Sum function can take 1 or many arguments and return sum of all the arguments passed.

 

sum.js

function sumAll(...numbers) {
  let sum = 0;
  for (let number of numbers) {
    sum += number;
  }
  return sum;
}

console.log(`sumAll(1) : ${sumAll(1)}`); 
console.log(`sumAll(1, 2) : ${sumAll(1, 2)}`); 
console.log(`sumAll(1, 2, 3) : ${sumAll(1, 2, 3)}`);

Output

sumAll(1) : 1
sumAll(1, 2) : 3
sumAll(1, 2, 3) : 6

In this example, the sumAll function takes a rest parameter numbers. All arguments passed to the function are collected into the numbers array. The function then iterates over this array and sums the values.

 

Example 2: Combining Rest Parameters with Other Parameters

You can also use rest parameters alongside regular parameters, but the rest parameter must be the last in the function definition.

 

mixedWithOtherParams.js

function introduce(greeting, ...names) {
  return `${greeting}, ${names.join(' and ')}!`;
}

// Output: Hello, Alice and Bob!
console.log(introduce('Hello', 'Hari', 'Ram')); 

// Output: Hi, John and Jane and Doe!
console.log(introduce('Hi', 'Hari', 'Ram', 'Krishna')); 

Output

Hello, Hari and Ram!
Hi, Hari and Ram and Krishna!

The introduce function takes a greeting and a rest parameter names. The greeting is a regular parameter, while names gathers the remaining arguments. The rest parameters are joined together with the word "and" to create a friendly greeting.

 

Rest Parameters vs arguments Object

Before rest parameters were introduced, the arguments object was used to handle multiple function arguments. However, rest parameters are preferred because:

 

1.   The arguments object is not a real array, so you have to convert it to an array if you want to use array methods.

2.   Rest parameters provide more clarity and flexibility, as they only capture the remaining arguments, not all arguments.

 

restParameterVsRegularParameter.js

function oldWay() {
  console.log(arguments);
}

function newWay(...args) {
  console.log(args); 
}

oldWay(1, 2, 3);
newWay(1, 2, 3);

Output

[Arguments] { '0': 1, '1': 2, '2': 3 }
[ 1, 2, 3 ]


 

Previous                                                    Next                                                    Home

Text Alignment in CSS: A Complete Guide with Examples

The text-align property in CSS is used to set the horizontal alignment of text within a block-level element, such as a paragraph, a heading, or a div. This property is essential for controlling how text is positioned within its containing element.

Syntax

selector {
    text-align: value;
}

Following are the possible values for text-align property.

 

1.   left: Aligns the text to the left. This is the default alignment in left-to-right (LTR) languages like English.

 

2.   right: Aligns the text to the right. Commonly used in right-to-left (RTL) languages like Arabic or Hebrew.

 

3.   center: Centers the text horizontally within its container.

 

4.   justify: Stretches the lines of text so that each line has equal width, making both the left and right edges of the text flush with the container edges. The last line is aligned left by default.

 

textAlign.html

<!-- html/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text Align Example</title>
    <style>
        .left-align p {
            text-align: left;
        }

        .right-align p {
            text-align: right;
        }

        .center-align p {
            text-align: center;
        }

        .justify-align p {
            text-align: justify;
        }

        p {
            font-size: 1.5em;
        }

        h1{
            color: darkblue;
        }
    </style>
</head>
<body>
    <div class="left-align">
        <h1>Left Aligned</h1>
        <p>CSS properties are the attributes used to control the presentation of elements on a webpage. Each property affects specific aspects of an element's appearance. Here’s a detailed look at some common CSS properties with examples.</p>
    </div>

    <div class="right-align">
        <h1>Right Aligned</h1>
        <p>CSS properties are the attributes used to control the presentation of elements on a webpage. Each property affects specific aspects of an element's appearance. Here’s a detailed look at some common CSS properties with examples.</p>
    </div>

    <div class="center-align">
        <h1>Center Aligned</h1>
        <p>CSS properties are the attributes used to control the presentation of elements on a webpage. Each property affects specific aspects of an element's appearance. Here’s a detailed look at some common CSS properties with examples.</p>
    </div>

    <div class="justify-align">
        <h1>Justified</h1>
        <p>CSS properties are the attributes used to control the presentation of elements on a webpage. Each property affects specific aspects of an element's appearance. Here’s a detailed look at some common CSS properties with examples.</p>
    </div>
</body>
</html>





Previous                                                    Next                                                    Home

Understanding href="#": What It Does and When to Use It

The href="#" attribute in HTML is commonly used in anchor (<a>) tags, and it serves a few specific purposes, mainly in navigation and link behavior.

When a user clicks on a link with href="#", the browser will scroll to the top of the current page or do nothing if already at the top. This happens because the # symbol is interpreted as a reference to the top of the document when no specific id is provided.

 

Example

<a href="#">Link To Top</a>

 

link-to-top.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Internal Linking Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
        nav {
            background-color: #4CAF50;
            color: white;
            padding: 15px;
            text-align: center;
            position: fixed;
            width: 100%;
            top: 0;
            left: 0;
        }
        nav a {
            color: white;
            margin: 0 15px;
            text-decoration: none;
            font-size: 18px;
        }
        .section {
            padding: 50px;
            margin-top: 50px; /* Avoid overlap with the fixed nav bar */
            height: 500px;
        }
        #section1 { background-color: #f4f4f4; }
        #section2 { background-color: #e2e2e2; }
        #section3 { background-color: #cfcfcf; }
        #section4 { background-color: #b2b2b2; }
        #section5 { background-color: #999; }
    </style>
</head>
<body>

    <!-- Navigation Bar -->
    <nav>
        <a href="#section1">Go to Section 1</a>
        <a href="#section2">Go to Section 2</a>
        <a href="#section3">Go to Section 3</a>
        <a href="#section4">Go to Section 4</a>
        <a href="#section5">Go to Section 5</a>
    </nav>

    <!-- Sections -->
    <div id="section1" class="section">
        <h2>Section 1</h2>
        <p>This is the content of section 1.</p>
    </div>

    <div id="section2" class="section">
        <h2>Section 2</h2>
        <p>This is the content of section 2.</p>
    </div>

    <div id="section3" class="section">
        <h2>Section 3</h2>
        <p>This is the content of section 3.</p>
    </div>

    <div id="section4" class="section">
        <h2>Section 4</h2>
        <p>This is the content of section 4.</p>
    </div>

    <div id="section5" class="section">
        <h2>Section 5</h2>
        <p>This is the content of section 5.</p>
    </div>

    <h2>
        <a href="#">Link To Top</a>
    </h2>
</body>
</html>

Open above page in the browser, scroll down to the end and click on the link ‘Link To Top’ to see the behavior.


 


JavaScript-Driven Links

href="#" is frequently used in conjunction with JavaScript to create interactive elements. The link itself doesn't lead anywhere, but JavaScript can be used to define actions that occur when the link is clicked (e.g., opening a model, triggering an event).

<a href="#" onclick="openModel()">Open Model</a>

In summary, when someone clicks this link, it will call the openModel() function (assuming that this function is defined in the JavaScript part of the code), which will likely display a model dialog box or perform some related action.

 

Using href="#" without preventing the default behavior can cause the page to jump to the top or introduce undesirable scrolling behavior. To avoid this, developers often use JavaScript to prevent the default action of the anchor tag.

<a href="#" onclick="someFunction(); return false;">Click Here</a>

(or)

<a href="#" onclick="someFunction(); event.preventDefault();">Click Here</a>


Previous                                                    Next                                                    Home