Retrieving information and implementing condition-based rendering using React's useEffect

I am currently developing a MERN stack application that retrieves information regarding college classes and presents it in a table format. The CoursesTable.js component is structured as follows:

import React, { useState, useEffect } from 'react';
import { Table } from 'react-materialize';
import axios from 'axios';

const CoursesTable = () => {

  const [courses, setCourses] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const coursesData = await axios.get('http://localhost:8001/')
      setCourses(coursesData.data)
    }
    fetchData()
  }, [])

  return (
    <Table>
      <thead>
        <tr>
          <th data-field="course-name">
            Name
          </th>
          <th data-field="course-prof">
            Prof.
          </th>
          <th data-field="course-code">
            Code
          </th>
        </tr>
      </thead>
      <tbody>
        {
          courses.length >= 1
          ? courses.map(course =>
              <tr key={course._id}>
                <td>
                  {course.name}
                </td>
                <td>
                  {course.prof}
                </td>
                <td>
                  {course.code}
                </td>
              </tr>
            )
          : <tr>
              <td>There is no course</td>
            </tr>
        }
      </tbody>
    </Table>
  );
}

export default CoursesTable;

To handle the scenario when courses is empty, I have implemented conditional rendering so that a message stating 'There is no course' is displayed. Once the array contains data, it is displayed within table rows.

However, I am facing an issue where the 'There is no course' message briefly appears for a few milliseconds even when courses is populated with data before being replaced by the actual content. How can I address this issue? Your assistance is greatly appreciated!

Answer №1

To ensure a smooth flow of data, you may want to include a conditional statement like the following:

import React, { useState, useEffect } from 'react';
import { Table } from 'react-materialize';
import axios from 'axios';

const CoursesTable = () => {

  const [courses, setCourses] = useState([]);
  const [isLoading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      const coursesData = await axios.get('http://localhost:8001/')
      setCourses(coursesData.data)
      setLoading(false);
    }
    fetchData()
  }, [])
  
  if(isLoading) { return <div> Loading ... </div>; };
  
  return (
    <Table>
      <thead>
        <tr>
          <th data-field="course-name">
            Name
          </th>
          <th data-field="course-prof">
            Prof.
          </th>
          <th data-field="course-code">
            Code
          </th>
        </tr>
      </thead>
      
      <tbody>
        {
          courses.length >= 1
          ? courses.map(course => 
              <tr key={course._id}>
                <td>
                  {course.name}
                </td>
                <td>
                  {course.prof}
                </td>
                <td>
                  {course.code}
                </td>
              </tr>
            )
          : <tr>
              <td>There is no course</td>
            </tr>
        }
      </tbody>
    </Table>
  );
}

export default CoursesTable;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React Jodit Editor experiencing focus loss with onchange event and useMemo functionality not functioning properly

I'm currently working on a component that includes a form with various inputs and a text editor, specifically Jodit. One issue I've encountered is that when there are changes in the Jodit editor's content, I need to retrieve the new HTML va ...

Vue: Storing selected list values in an array

I am working on a Vue application where I need to select two elements from a list component and place them inside an array. Currently, I have my list set up with selection functionality thanks to Vuetify. I have bound the selected items to an array using v ...

What is the best way to show the user profile on a Forum?

I am struggling to figure out how to display the username of a user on my forum page. I currently only have access to the user's ID and need help in extracting their name instead. It seems that I lack knowledge about mongoose and could really benefit ...

In what way can I decipher a section of the URL query string within my AngularJS application?

Here is a snippet of code that I am working with: var search = $location.search(); if (angular.isDefined(search.load) && search.load != null) { if (search.load = "confirmEmail") authService.confirmEmailUserId = search.userI ...

StartsWith() function failing when used in conjunction with takeWhile()

I'm trying to iterate over an Immutable List and create a new list containing only the entries that start with a specific string. In this case, I want to find all states that begin with the letter 'D'. However, instead of returning a list wi ...

If the MUI autocomplete is unable to retrieve the value from the multiple attribute, it will either return 0 or remain undefined

When using the MUI Autocomplete component with the 'multiple' attribute, the value prop may return 0 or undefined when selecting an option. <Autocomplete value={v.education} onChange={handleEducationChange} className={classes.textOutline ...

How do I access the previous and current values in a v-for loop in Vue.js in order to compare them?

I am working on a structural component that involves looping through a list and performing certain actions based on the items: .... <template v-for="(item, INDEX) in someList"> <template v-if="thisIsArrayList(item)"> ...

Error: Attempting to access a property of an undefined value (referencing '8') was unsuccessful

Hello everyone, I am new to posting and identify as a junior Frontend developer. I'm encountering a confusing issue with the InputLabel from Material UI (ver. 5) on a specific section of the website I'm working on. On the homepage, I successfully ...

Reading properties of undefined in React is not possible. The log method only functions on objects

I'm currently facing an issue while developing a weather website using the weatherapi. When I try to access properties deeper than the initial object of location, like the city name, it throws an error saying "cannot read properties of undefined." Int ...

What is the best way to create a clickable background for a modal window?

I am looking to add a chatbox feature to my website and have been utilizing Bootstrap Modal for this purpose. My goal is to keep the modal open even when the user clicks outside of it, while still allowing them to interact with the background of the websi ...

An error was encountered when attempting to reference an external JavaScript script in the document

Could someone please provide guidance on how to utilize the document method in an external .js file within Visual Studio Code? This is what I have tried so far: I have created an index.html file: <!DOCTYPE html> <html lang="en"> <head> ...

I am currently struggling to make the userID route parameter function correctly with react-router-relay

I've been diving into the world of React Relay and GraphQL with react-relay-router, but I'm having trouble getting the params in my routes to function correctly. Specifically, I'm struggling with the "/Maps/:userID" route. Let me share my r ...

Switch between divs based on the current selection

var header = $("#accordion"); $.each(data, function () { header.append("<a id='Headanchor' href='javascript:toggleDiv($(this));'>" + this.LongName + "</a>" + "<br />", "&l ...

Restart the _.after function counter

Despite my efforts to search online, I couldn't find a solution for resetting the _.after counter once the code inside has been executed. The goal here is to have the alert box appear only on every 5th click of the button: var cb; cb = _.after(4, fu ...

What is the correct way to format responses written within response.write() in NodeJS?

Just starting out with NodeJS and express and following a tutorial on displaying two headings in the browser. Came across an issue where using res.send() twice wasn't working, so my instructor introduced me to the write method. Interestingly, when she ...

The occurrence of the page constantly refreshing and altering the query parameters 'state' and 'session' in the URL is a common issue encountered while integrating React with keycloak

I've been experimenting with using React alongside Keycloak. I've set up the realm, users, and client successfully. However, whenever I run npm start to launch my react project, the page keeps refreshing every second and the state changes. For e ...

Changing divider color in Material-UI with React

I need some assistance with changing the color of the divider component from the material ui framework. I have successfully changed colors for other components using the useStyles() method like this: const useStyles = makeStyles(theme => ({ textPad ...

Trouble Arising from Making a POST Request to Spotify's API

I am currently developing a web application that allows users to search the Spotify Library, add songs to playlists, and then save those playlists to their Spotify Accounts. Almost everything is functioning correctly except for the saving of playlists thro ...

What is the best way to link optional and undefined paths in AngularJS routing?

When it comes to AngularJS routing, I have a question. How can we combine the use of a star (*) to match paths with slashes and a question mark (?) to match optional paths? Specifically, I am looking to match both /admin/tasks and /admin/tasks/arbitrary/pa ...