Reactjs (javascript) how do I not see that the list is empty (Before) api gets called

componentdidupdate
react hooks
getderivedstatefromprops
react suspense
useeffect
react component lifecycle diagram
react native lifecycle
componentdidupdate setstate

This is the current code, when I load the list page, for a moment it says "No List Items Found", it then loads the items from the backend api afterwards and shows those items (the above message dissapears)

import React, { Component } from 'react';

class List extends Component {

    // Initialize the state
    constructor(props){
        super(props);
        this.state = {
            list: [],
            isFetchedFromServer:false
        }
    }

    // Fetch the list on first mount
    componentDidMount() {
        this.getList();
    }

    // Retrieves the list of items from the Express app
    getList = () => {
        fetch('/api/getList')
            .then(res => res.json())
            .then(list => this.setState({ list }))
            .then(this.state.isFetchedFromServer= true)
    }

    render() {
        const { list } = this.state;

        return (
            <div className="App">
            <h1>List of Items</h1>
        {/* Check to see if any items are found*/}
        {list.length ? (
            <div>
            {/* Render the list of items */}
            {list.map((item) => {
                    return(
                        <div>
                        {item}
                        </div>
                );
                })}
            </div>
        ) : (
        <div className={((this.state.list != undefined) &&( this.state.list != null)) ? '' : 'hidden'}>
        <h2>No List Items Found</h2>
        </div>
        )
        }
    </div>
    );
    }
}

export default List;

I would like to only see no list items found when it has returned from the backend call empty.

Please assist me in doing so.

Declare a flag and update it after fetch is completed.

this.isShowMessage: false;

componentDidMount() {
        this.getList();
        this.isShowMessage: (this.state.list == null);
    }

And hide your div accordingly.

<div>
   {(this.isShowMessage) && <h2>No List Items Found</h2>}
</div>

Fetching Data and Updating State in a React Class, Have you ever needed to render data in your React component that comes One of the components in this application lists every book in the The book details need to come from a Rest API, so let's see how to do The user will not see the intermediate state. Then componentDidMount() is called 4. The fetchData function fetches information from the top-level GitHub API. Since fetch returns a promise, to consume that promise we do a .then call on the result of fetch and supply a callback function in there. The callback function will receive the raw response from the API.

As the Api is an Async Call , it initially says that the List is empty and after the response , the list is filled with objects. You may have to add a boolean APIProcessing in the state with initial value as true while the objects are still getting fetched from the database . After that you need to set to false and display the list

React.Component – React, This page contains a detailed API reference for the React component class definition These methods are called in the following order when a component is being re-rendered The render() function should be pure, meaning that it does not modify is invoked before rendering when new props or state are being received. For what it's worth: I was wrestling with this because I thought I needed a manual re-render, and finally realized that I simply needed to move an externally held variable into a state hook and leverage the setting function, which fixed all my problems without a re-render.

What you are facing is absolutely fine. This is happening because it might take a small time for you app to get response from the API.

So till there is a response the length of this.state.list will be 0. Until that

No List Items Found
will be shown.

You can negate the statement just to show it.

Hope this helps!

React Top-Level API – React, We recommend using JSX to describe what your UI should look like. You will not typically invoke the following methods directly if you are using JSX. Suspense lets components “wait” for something before rendering. Component API Reference for a list of methods and properties related to the base forwardRef call. Try it on CodePen. This code displays a bullet list of numbers between 1 and 5. Basic List Component . Usually you would render lists inside a component.. We can refactor the previous example into a component that accepts an array of numbers and outputs a list of elements.

What you’re missing is a Boolean flag ‘isLoading’ in component state.

In your componentDidMount, set it to true. When your fetch has finished, set it to false.

Then, only show ‘No list items found.’ if isLoading is false and the list is empty.

Suspense for Data Fetching (Experimental) – React, Suspense lets your components “wait” for something before they can render. In this example, two components wait for an asynchronous API call to fetch If you' re looking for a practical guide to get started today, check out the Relay Guide! This makes them easier to understand if you're not familiar with GraphQL, but they� A more proper ES5 solution would be Object.getOwnPropertyNames(obj).length == 0 because Object.keys only gets the enumerable properties. In ES5 we have the power of defining property attributes, we could have an object with non-enumerable properties and Object.keys will just return an empty array

AJAX and APIs – React, How can I make an AJAX call? You should populate data with AJAX calls in the componentDidMount lifecycle The example API returns a JSON object like this: Component { constructor(props) { super(props); this.state = { error: null, Note: it's important to handle errors here // instead of a catch() block so that we don't� Since component logic is written in JavaScript instead of templates, you can easily pass rich data through your app and keep state out of the DOM. Learn Once, Write Anywhere We don’t make assumptions about the rest of your technology stack, so you can develop new features in React without rewriting existing code.

React Lifecycle Methods Render And ComponentDidMount, If we are talking about lifecycle methods in React.js then render() is the most used It is seen as a normal function but render() function has to return something there is no JSX for the return then null would be perfect, but must return something. API then API call should be placed in this lifecycle method, and then we get� JSX is used with ReactJS as it is very similar to HTML and it gives programmers feel of using HTML whereas it ultimately transpiles to a javascript file. Writing a for-loop and specifying function as {this.props.removeTaskFunction(todo)} will execute the functions whenever the loop is triggered .

React.js cheatsheet, React.Component � render() � componentDidMount() � props/state Use the React.js jsfiddle to start hacking. (or the unofficial jsbin) With Babel you can use proposal-class-fields and get rid of constructor See: Component API componentWillUnmount(), Before DOM removal # These are not called for initial renders. We can see from this documentation that it tells us we can make requests with curl or regular REST calls, but we might not have a clue how to do that yet. Obtaining the API endpoint. To get started, let's scroll to the films section. On the right you'll see GET /films. It will show us the URL of our API endpoint, https://ghibliapi.herokuapp.com

Comments
  • Add the code of whole component. Also what exactly do you want? You api returns you an empty list but it's not rendering No list items found div?
  • I think we should have the variable flag inside the state. what do you say
  • Yep, better to keep it inside the state.
  • Nope, I still see that message, The only change I did was in componentDidMount this.state.isFetchedFromServer = (this.state.list != null); .
  • I even defined a css class called hidden but nope. I still see that message. Let me post my code above in the OP
  • I solved it by moving the hidden ahead to the other side. basically its your solution <div className={(list)? 'hidden' : ''}>
  • Sure, I will try to add a boolean flag