Open In App

How to display values from database in real time without refreshing the webpage ?

Last Updated : 02 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Display values from database in real time without refreshing the webpage simply refers to auto fetch and re-rendering the data if there is any change due to user interaction or any update in the data from the APIs. In React JS, it can be done by using the states that re-render the UI on updates.

Prerequisites

Approach

To display values from the database in real-time without refreshing the webpage we will be using React JS Hooks that manage and update the states in realtime in React Functional components. useState rerenders the component on state update and useEffect calls and executes the code when there are any changes in the dependency array and update the component render on UI. The data from fetch methods is stored as an array and is displayed using array.map on UI.

Note: We can also use Axios to fetch the data. Visit here to know more.

Steps to create React Application

Step 1: Create a React application using the following command:

npx create-react-app app-name 

Step 2: After creating your project folder(i.e. my-app), move to it by using the following command:

cd app-name

Project Structure:

Example: Fetching user data from the api using fetch method form the api and display into card

Javascript




// Filename - App.js
 
import { useEffect, useState } from "react";
 
function App() {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);
    const container = {
        display: "flex",
        flexDirection: "row",
        flexWrap: "wrap",
        margin: "4% auto",
    };
 
    useEffect(() => {
        // API to fetch some dummy data
        fetch("https://reqres.in/api/users?page=1")
            .then((resp) => resp.json())
            .then((apiData) => {
                setData(apiData.data);
                console.log(apiData);
                setLoading(false);
            });
    }, []); // Dependency-array
 
    return (
        <div
            style={{ textAlign: "center", margin: "auto" }}
        >
            <h1 style={{ color: "green" }}>
                GeeksforGeeks
            </h1>
            <h3>
                Display values from database without
                reloading...
            </h3>
            {loading ? (
                <h4>Loading Data...</h4>
            ) : (
                <div style={container}>
                    {data.map((item) => {
                        return (
                            <div
                                key={item.id}
                                style={{
                                    minWidth: "30rem",
                                    margin: "1% auto",
                                    padding: "1%",
                                    boxShadow:
                                        "0 2px 5px grey",
                                    display: "flex",
                                    fontSize: "larger",
                                    margin: "1% auto",
                                }}
                            >
                                <span>
                                    <img
                                        style={{
                                            width: "100px",
                                            borderRadius:
                                                "50px",
                                        }}
                                        src={item.avatar}
                                    ></img>
                                </span>
                                <span
                                    style={{
                                        textAlign: "left",
                                        margin: "auto",
                                    }}
 
                                    // style={style}
                                >
                                    <div>
                                        <b>Name: </b>
                                        {
                                            item.first_name
                                        }{" "}
                                        {item.last_name} {}
                                    </div>
                                    <div>
                                        <b>Email: </b>{" "}
                                        {item.email}
                                    </div>
                                </span>
                            </div>
                        );
                    })}
                </div>
            )}
        </div>
    );
}
 
export default App;


Step to run the application: Run the following command to start the application:

npm start

Output: This output will be visible on http://localhost:3000/ on browser window.

Peek-2023-10-20-12-04

Note: The useEffect hook will automatically run the code for fetching data so you don’t have to reload the page again and again.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads