Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js - clean way to differentiate loading/empty states in Render

I have my component:

getInitialState() {
    return {
        items: []
    };
},

componentDidMount() {
    // make remote call to fetch `items`
    this.setState({
        items: itemsFromServer
    })
},

render(){
    if(!this.state.items.length){
        // show empty state
    }
    // output items
}

Extremely contrived/sandboxed, but this is the general idea. When you first load this component, you see a flash of the "empty state" HTML, as the server hasn't yet returned any data.

Has anyone got an approach/a React Way™ of handling whether there is actually no data vs. showing a loading state?

like image 645
benhowdle89 Avatar asked Jun 22 '15 22:06

benhowdle89


1 Answers

I've just been rendering a empty span element but you could just as easily render a CSS spinner of some kind to show it's loading.

if(!this.state.items.length){
    return(<div class="spinner-loader">Loading…</div>);
}

http://www.css-spinners.com/

You may also want to consider what happens if your response comes back with no results. I would use (this.state.items === null) to indicate that you are waiting for results and an empty array/collection (!this.state.items.length) to indicate that no results were returned.

like image 93
David Forshner Avatar answered Oct 19 '22 22:10

David Forshner