How to handle empty object before mount in ReactJS ?
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:
Step 3: Install modules
npm install react-spinners axios
Step 3: Run the development server by using the following command:
Project Structure: It will look like the following.
Example: Add the following code in respective files.
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.