Wednesday, July 3, 2024
HomeLanguagesReactHow to handle empty object before mount in ReactJS ?

How to handle empty object before mount in ReactJS ?

When working with ReactJS, it’s common to encounter situations where you need to handle empty objects or uninitialized data before rendering components. In this article, we will explore different approaches to handle empty objects before mounting in ReactJS and discuss best practices for dealing with this scenario.

However, these processes often involve scenarios where certain data must be present in the app’s state. For instance, during user authentication, it is crucial to log in or register the user and maintain the application state to indicate that the user is logged in and has access to protected data. Similarly, 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. In this article, we will explore how to effectively handle this situation using a practical example.

Creating React Application And Installing Module:

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 install react-spinners axios

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

npm start

Project Structure: It will look like the following.

Project Strcuture

Example: Add the following code in respective files.

App.js

Javascript




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;


Explanation: Here we have made two states i.e. an array of fetched jokes and the second is loading. We will set loading to be true before fetching the joke and set it to be false after the operation has been completed. And there is one conditional JSX that will render a spinner on the basis of this loading state. When loading is true it will show only the spinner and when it is set to false it will render the jokes array which is the data that we want to show. This conditional JSX is not complicated we have just used a ternary operator. We have set up an onClick handler that will call the fetchData() function which is responsible for fetching a joke and adding it to the state ( jokes array ). The approach to handle empty objects or arrays before mounting is that we can declare a variable that will hold data on the basis of the initial condition i.e. when the array’s length is at least 1 then we have to show the jokes in proper format else we can show some text which is helpful for the user on how to get data by interacting to the UI of the web app. It also gives a good user experience.

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

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!

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments