Open In App

How to handle empty object before mount in ReactJS ?

Last Updated : 30 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

When working with ReactJS, it’s common to encounter situations where you need to handle empty objects or uninitialized data before rendering components. when fetching data, it is necessary to load the data and perform various operations on it. However, a challenge arises when the app state lacks the required data, either because it hasn’t been fetched yet or is currently being fetched.

Prerequisites

Approach

To handle empty object before mount in ReactJS we will be using a custom loading screen. react-spinners is a library that provide the loading component and can be used easily in the react projects. We will fetch data from an API using axios and untill that data is loaded there will appear a loading screen till the object is empty and data isn’t completed loading.

Creating React Application

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

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Step 3:  Install modules

npm i react-spinners axios

Project Structure

It will look like the following.

Project Strcuture

Dependencies list after installing libraries

{
"dependencies": {
"@material-ui/core": "^4.12.4",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"react-spinners": "^0.13.8",
"web-vitals": "^2.1.4"
}
}

Example: Here we are using a loding component till the object is empty or the data fetch is in process.

Javascript




// Filename - App.js
 
import { useState } from "react";
import axios from "axios";
import ClipLoader from "react-spinners/ClipLoader";
 
function App() {
    const [Joke, setJoke] = useState([]);
    const [loading, setLoading] = useState(false);
    const fetchData = async () => {
        setLoading(true);
        var options = {
            method: "GET",
            headers: {
                accept: "application/json",
                "x-rapidapi-host":
                    "matchilling-chuck-norris-jokes-v1.p.rapidapi.com",
                "x-rapidapi-key":
                    "ffc2438edbmsh0a88b634e6e77a7p123125jsnfb163d4d72f7",
            },
        };
 
        let data = await axios.request(options);
        console.log("data,", data.data);
        setJoke([...Joke, data.data]);
        setLoading(false);
    };
 
    let jokesArray;
    if (Joke.length >= 1) {
        jokesArray = Joke.map((el) => {
            return (
                <div
                    key={el.id}
                    style={{
                        width: "350px",
                        display: "flex",
                        flexDirection: "column",
                        alignItems: "center",
                        margin: "10px",
                        border: "2px solid green",
                        padding: "5px",
                    }}
                >
                    <div style={{ width: "50px" }}>
                        <img
                            src={el.icon_url}
                            style={{ objectFit: "cover" }}
                            alt=""
                        />
                    </div>
                    <h4>{el.value} </h4>
                </div>
            );
        });
    } else {
        jokesArray = "Click on the button to fetch Jokes";
    }
 
    const handleClick = () => {
        fetchData();
    };
 
    return (
        <div
            className="App"
            style={{
                margin: "20px",
                padding: "20px",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                flexDirection: "column",
            }}
        >
            <div>
                <button
                    onClick={handleClick}
                    style={{
                        padding: "10px",
                        outline: "none",
                        border: "none",
                        backgroundColor: "green",
                        opacity: ".7",
                        borderRadius: "10px",
                        color: "white",
                        cursor: "pointer",
                    }}
                >
                    Fetch Joke
                </button>
            </div>
            <div>
                {loading ? <ClipLoader /> : jokesArray}
            </div>
        </div>
    );
}
 
export default App;


Step 3: Run the development server by using the following command:

npm start

Output: Notice that the text changes when clicking on the button, which initially displays how to fetch jokes.



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

Similar Reads