Saturday, November 16, 2024
Google search engine
HomeLanguagesHow to display values from database in real time without refreshing the...

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

In this article, we will see how to display values from a database without refreshing the web page. Let’s say in our web app, we have one button after clicking that button a function gets fire and fetches data from the database. Or in React web app we can use hooks that automatically fetch data every time the page gets opened for example we can useEffect hook from React.

Creating React App: 

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: It will look like this.

Using useEffect hooks: How to fetch data when a component mounts, how to run code when state changes or when a prop changes, how to set up timers or intervals. The useEffect runs after every render (by default), and can optionally clean up for itself before it runs again. So using this hook we can display values from the database in real-time without reloading the webpage. 

Syntax: Following is the syntax of useEffect hook:

useEffect(() => {
    // Your code
}, []) // Dependency-array

Fetching data from database via API: Let’s say we have an API that connects from the database, here we used random API which provides dummy data. After clicking the handleFetchData function data will fetch and you can see it at your console.

const handleFetchData = async (e) => {
  // Put the endpoint of Api
  fetch('API_URL_ENDPOINT')
    .then((resp) => resp.json())
    .then((data) => console.log(data))
    .catch((e) => console.log(e));
};

Implementation: Write down the following code in the respective file.

App.js

Javascript




import { useEffect, useState } from 'react';
 
function App() {
    const [data, setData] = useState([]);
 
    useEffect(() => {
        // API to fetch some dummy data
        fetch('https://reqres.in/api/users?page=2')
            .then((resp) => resp.json())
            .then((apiData) => {
                setData(apiData.data);
            });
    }, []); // Dependency-array
 
    const style = {
        padding: '5px',
        display: 'block',
        color: 'green',
        border: '1px solid black',
    };
 
    return (
        <div style={{ textAlign: 'center' }}>
            <h1>This is React WebApp </h1>
            <h5>Display values from database without reloading...</h5>
 
            {data.map((item) => {
                return (
                    <span style={style} key={item.id}>
                        {item.email}
                    </span>
                );
            })}
        </div>
    );
}
 
export default App;


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

npm start

Output:

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments