Skip to content
Related Articles

Related Articles

How to handle empty object before mount in ReactJS ?

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 03 Mar, 2022
View Discussion
Improve Article
Save Article

In this article, we will see how to handle empty objects before mounting in ReactJs. The problem is that when we do any data fetching or user authentication. They require some sort of data to be maintained in the app in the case of user authentication we have to log the user in or register and then maintain an app state that the user is logged in and now he has the right to access the protected data. Whereas in the case of data fetching we have to load the data first and then do various operations on it. But what about the app state when the data is not fetched or is begin fetched. We will understand with an example how to handle this situation. 

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




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 clicked on the button, which initially displays how to fetch jokes.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!